Coverage Report

Created: 2024-07-31 01:10

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.91.0 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - See links below.
6
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
7
// - Read top of imgui.cpp for more details, links and comments.
8
9
// Resources:
10
// - FAQ ........................ https://dearimgui.com/faq (in repository as docs/FAQ.md)
11
// - Homepage ................... https://github.com/ocornut/imgui
12
// - Releases & changelog ....... https://github.com/ocornut/imgui/releases
13
// - Gallery .................... https://github.com/ocornut/imgui/issues/7503 (please post your screenshots/video there!)
14
// - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there)
15
//   - Getting Started            https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code)
16
//   - Third-party Extensions     https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more)
17
//   - Bindings/Backends          https://github.com/ocornut/imgui/wiki/Bindings (language bindings, backends for various tech/engines)
18
//   - Glossary                   https://github.com/ocornut/imgui/wiki/Glossary
19
//   - Debug Tools                https://github.com/ocornut/imgui/wiki/Debug-Tools
20
//   - Software using Dear ImGui  https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui
21
// - Issues & support ........... https://github.com/ocornut/imgui/issues
22
// - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps)
23
24
// For first-time users having issues compiling/linking/running/loading fonts:
25
// please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
26
// Everything else should be asked in 'Issues'! We are building a database of cross-linked knowledge there.
27
28
// Copyright (c) 2014-2024 Omar Cornut
29
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
30
// See LICENSE.txt for copyright and licensing details (standard MIT License).
31
// This library is free but needs your support to sustain development and maintenance.
32
// Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts.
33
// PLEASE reach out at omar AT dearimgui DOT com. See https://github.com/ocornut/imgui/wiki/Funding
34
// Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
35
36
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
37
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
38
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
39
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
40
// to a better solution or official support for them.
41
42
/*
43
44
Index of this file:
45
46
DOCUMENTATION
47
48
- MISSION STATEMENT
49
- CONTROLS GUIDE
50
- PROGRAMMER GUIDE
51
  - READ FIRST
52
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
53
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
54
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
55
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
56
- API BREAKING CHANGES (read me when you update!)
57
- FREQUENTLY ASKED QUESTIONS (FAQ)
58
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
59
60
CODE
61
(search for "[SECTION]" in the code to find them)
62
63
// [SECTION] INCLUDES
64
// [SECTION] FORWARD DECLARATIONS
65
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
66
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
67
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
68
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
69
// [SECTION] MISC HELPERS/UTILITIES (File functions)
70
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
71
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
72
// [SECTION] ImGuiStorage
73
// [SECTION] ImGuiTextFilter
74
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
75
// [SECTION] ImGuiListClipper
76
// [SECTION] STYLING
77
// [SECTION] RENDER HELPERS
78
// [SECTION] INITIALIZATION, SHUTDOWN
79
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
80
// [SECTION] ID STACK
81
// [SECTION] INPUTS
82
// [SECTION] ERROR CHECKING
83
// [SECTION] ITEM SUBMISSION
84
// [SECTION] LAYOUT
85
// [SECTION] SCROLLING
86
// [SECTION] TOOLTIPS
87
// [SECTION] POPUPS
88
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
89
// [SECTION] DRAG AND DROP
90
// [SECTION] LOGGING/CAPTURING
91
// [SECTION] SETTINGS
92
// [SECTION] LOCALIZATION
93
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
94
// [SECTION] DOCKING
95
// [SECTION] PLATFORM DEPENDENT HELPERS
96
// [SECTION] METRICS/DEBUGGER WINDOW
97
// [SECTION] DEBUG LOG WINDOW
98
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
99
100
*/
101
102
//-----------------------------------------------------------------------------
103
// DOCUMENTATION
104
//-----------------------------------------------------------------------------
105
106
/*
107
108
 MISSION STATEMENT
109
 =================
110
111
 - Easy to use to create code-driven and data-driven tools.
112
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
113
 - Easy to hack and improve.
114
 - Minimize setup and maintenance.
115
 - Minimize state storage on user side.
116
 - Minimize state synchronization.
117
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
118
 - Efficient runtime and memory consumption.
119
120
 Designed primarily for developers and content-creators, not the typical end-user!
121
 Some of the current weaknesses (which we aim to address in the future) includes:
122
123
 - Doesn't look fancy.
124
 - Limited layout features, intricate layouts are typically crafted in code.
125
126
127
 CONTROLS GUIDE
128
 ==============
129
130
 - MOUSE CONTROLS
131
   - Mouse wheel:                   Scroll vertically.
132
   - SHIFT+Mouse wheel:             Scroll horizontally.
133
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
134
   - Click ^, Double-Click title:   Collapse window.
135
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
136
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
137
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
138
139
 - TEXT EDITOR
140
   - Hold SHIFT or Drag Mouse:      Select text.
141
   - CTRL+Left/Right:               Word jump.
142
   - CTRL+Shift+Left/Right:         Select words.
143
   - CTRL+A or Double-Click:        Select All.
144
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
145
   - CTRL+Z, CTRL+Y:                Undo, Redo.
146
   - ESCAPE:                        Revert text to its original value.
147
   - On OSX, controls are automatically adjusted to match standard OSX text editing 2ts and behaviors.
148
149
 - KEYBOARD CONTROLS
150
   - Basic:
151
     - Tab, SHIFT+Tab               Cycle through text editable fields.
152
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
153
     - CTRL+Click                   Input text into a Slider or Drag widget.
154
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
155
     - Tab, SHIFT+Tab:              Cycle through every items.
156
     - Arrow keys                   Move through items using directional navigation. Tweak value.
157
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
158
     - Enter                        Activate item (prefer text input when possible).
159
     - Space                        Activate item (prefer tweaking with arrows when possible).
160
     - Escape                       Deactivate item, leave child window, close popup.
161
     - Page Up, Page Down           Previous page, next page.
162
     - Home, End                    Scroll to top, scroll to bottom.
163
     - Alt                          Toggle between scrolling layer and menu layer.
164
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
165
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
166
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
167
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
168
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
169
170
 - GAMEPAD CONTROLS
171
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
172
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
173
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
174
   - Backend support: backend needs to:
175
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
176
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
177
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
178
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
179
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
180
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
181
182
 - REMOTE INPUTS SHARING & MOUSE EMULATION
183
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
184
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
185
     in order to share your PC mouse/keyboard.
186
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
187
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
188
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
189
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
190
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
191
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
192
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
193
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
194
195
196
 PROGRAMMER GUIDE
197
 ================
198
199
 READ FIRST
200
 ----------
201
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
202
 - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone!
203
   The UI can be highly dynamic, there are no construction or destruction steps, less superfluous
204
   data retention on your side, less state duplication, less state synchronization, fewer bugs.
205
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
206
   Or browse https://pthom.github.io/imgui_manual_online/manual/imgui_manual.html for interactive web version.
207
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
208
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
209
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
210
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
211
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
212
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
213
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
214
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
215
   If you get an assert, read the messages and comments around the assert.
216
 - This codebase aims to be highly optimized:
217
   - A typical idle frame should never call malloc/free.
218
   - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible.
219
   - We put particular energy in making sure performances are decent with typical "Debug" build settings as well.
220
     Which mean we tend to avoid over-relying on "zero-cost abstraction" as they aren't zero-cost at all.
221
 - This codebase aims to be both highly opinionated and highly flexible:
222
   - This code works because of the things it choose to solve or not solve.
223
   - C++: this is a pragmatic C-ish codebase: we don't use fancy C++ features, we don't include C++ headers,
224
     and ImGui:: is a namespace. We rarely use member functions (and when we did, I am mostly regretting it now).
225
     This is to increase compatibility, increase maintainability and facilitate use from other languages.
226
   - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
227
     See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
228
     We can can optionally export math operators for ImVec2/ImVec4 using IMGUI_DEFINE_MATH_OPERATORS, which we use internally.
229
   - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction
230
     (so don't use ImVector in your code or at our own risk!).
231
   - Building: We don't use nor mandate a build system for the main library.
232
     This is in an effort to ensure that it works in the real world aka with any esoteric build setup.
233
     This is also because providing a build system for the main library would be of little-value.
234
     The build problems are almost never coming from the main library but from specific backends.
235
236
237
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
238
 ----------------------------------------------
239
 - Update submodule or copy/overwrite every file.
240
 - About imconfig.h:
241
   - You may modify your copy of imconfig.h, in this case don't overwrite it.
242
   - or you may locally branch to modify imconfig.h and merge/rebase latest.
243
   - or you may '#define IMGUI_USER_CONFIG "my_config_file.h"' globally from your build system to
244
     specify a custom path for your imconfig.h file and instead not have to modify the default one.
245
246
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
247
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
248
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
249
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
250
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
251
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
252
   likely be a comment about it. Please report any issue to the GitHub page!
253
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
254
 - Try to keep your copy of Dear ImGui reasonably up to date!
255
256
257
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
258
 ---------------------------------------------------------------
259
 - See https://github.com/ocornut/imgui/wiki/Getting-Started.
260
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
261
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
262
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
263
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
264
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
265
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
266
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
267
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
268
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
269
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
270
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
271
272
273
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
274
 --------------------------------------
275
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
276
 The sub-folders in examples/ contain examples applications following this structure.
277
278
     // Application init: create a dear imgui context, setup some options, load fonts
279
     ImGui::CreateContext();
280
     ImGuiIO& io = ImGui::GetIO();
281
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
282
     // TODO: Fill optional fields of the io structure later.
283
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
284
285
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
286
     ImGui_ImplWin32_Init(hwnd);
287
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
288
289
     // Application main loop
290
     while (true)
291
     {
292
         // Feed inputs to dear imgui, start new frame
293
         ImGui_ImplDX11_NewFrame();
294
         ImGui_ImplWin32_NewFrame();
295
         ImGui::NewFrame();
296
297
         // Any application code here
298
         ImGui::Text("Hello, world!");
299
300
         // Render dear imgui into screen
301
         ImGui::Render();
302
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
303
         g_pSwapChain->Present(1, 0);
304
     }
305
306
     // Shutdown
307
     ImGui_ImplDX11_Shutdown();
308
     ImGui_ImplWin32_Shutdown();
309
     ImGui::DestroyContext();
310
311
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
312
313
     // Application init: create a dear imgui context, setup some options, load fonts
314
     ImGui::CreateContext();
315
     ImGuiIO& io = ImGui::GetIO();
316
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
317
     // TODO: Fill optional fields of the io structure later.
318
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
319
320
     // Build and load the texture atlas into a texture
321
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
322
     int width, height;
323
     unsigned char* pixels = nullptr;
324
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
325
326
     // At this point you've got the texture data and you need to upload that to your graphic system:
327
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
328
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
329
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
330
     io.Fonts->SetTexID((void*)texture);
331
332
     // Application main loop
333
     while (true)
334
     {
335
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
336
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
337
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
338
        io.DisplaySize.x = 1920.0f;             // set the current display width
339
        io.DisplaySize.y = 1280.0f;             // set the current display height here
340
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
341
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
342
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
343
344
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
345
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
346
        ImGui::NewFrame();
347
348
        // Most of your application code here
349
        ImGui::Text("Hello, world!");
350
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
351
        MyGameRender(); // may use any Dear ImGui functions as well!
352
353
        // Render dear imgui, swap buffers
354
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
355
        ImGui::EndFrame();
356
        ImGui::Render();
357
        ImDrawData* draw_data = ImGui::GetDrawData();
358
        MyImGuiRenderFunction(draw_data);
359
        SwapBuffers();
360
     }
361
362
     // Shutdown
363
     ImGui::DestroyContext();
364
365
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
366
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
367
 Please read the FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" about this.
368
369
370
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
371
 ---------------------------------------------
372
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
373
374
    void MyImGuiRenderFunction(ImDrawData* draw_data)
375
    {
376
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
377
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
378
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
379
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
380
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
381
       ImVec2 clip_off = draw_data->DisplayPos;
382
       for (int n = 0; n < draw_data->CmdListsCount; n++)
383
       {
384
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
385
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
386
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
387
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
388
          {
389
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
390
             if (pcmd->UserCallback)
391
             {
392
                 pcmd->UserCallback(cmd_list, pcmd);
393
             }
394
             else
395
             {
396
                 // Project scissor/clipping rectangles into framebuffer space
397
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
398
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
399
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
400
                     continue;
401
402
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
403
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
404
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
405
                 // - Clipping coordinates are provided in imgui coordinates space:
406
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
407
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
408
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
409
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
410
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
411
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
412
413
                 // The texture for the draw call is specified by pcmd->GetTexID().
414
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
415
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
416
417
                 // Render 'pcmd->ElemCount/3' indexed triangles.
418
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
419
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
420
             }
421
          }
422
       }
423
    }
424
425
426
 API BREAKING CHANGES
427
 ====================
428
429
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
430
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
431
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
432
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
433
434
(Docking/Viewport Branch)
435
 - 2024/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
436
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
437
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
438
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
439
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
440
441
 - 2024/07/25 (1.91.0) - obsoleted GetContentRegionMax(), GetWindowContentRegionMin() and GetWindowContentRegionMax().
442
                         you should never need those functions. you can do everything with GetCursorScreenPos() and GetContentRegionAvail() in a more simple way.
443
                            - instead of:  GetWindowContentRegionMax().x - GetCursorPos().x
444
                            - you can use: GetContentRegionAvail().x
445
                            - instead of:  GetWindowContentRegionMax().x + GetWindowPos().x
446
                            - you can use: GetCursorScreenPos().x + GetContentRegionAvail().x // when called from left edge of window
447
                            - instead of:  GetContentRegionMax()
448
                            - you can use: GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos() // right edge in local coordinates
449
                            - instead of:  GetWindowContentRegionMax().x - GetWindowContentRegionMin().x
450
                            - you can use: GetContentRegionAvail() // when called from left edge of window
451
 - 2024/07/15 (1.91.0) - renamed ImGuiSelectableFlags_DontClosePopups to ImGuiSelectableFlags_NoAutoClosePopups. (#1379, #1468, #2200, #4936, #5216, #7302, #7573)
452
                         (internals: also renamed ImGuiItemFlags_SelectableDontClosePopup into ImGuiItemFlags_AutoClosePopups with inverted behaviors)
453
 - 2024/07/15 (1.91.0) - obsoleted PushButtonRepeat()/PopButtonRepeat() in favor of using new PushItemFlag(ImGuiItemFlags_ButtonRepeat, ...)/PopItemFlag().
454
 - 2024/07/02 (1.91.0) - commented out obsolete ImGuiModFlags (renamed to ImGuiKeyChord in 1.89). (#4921, #456)
455
                       - commented out obsolete ImGuiModFlags_XXX values (renamed to ImGuiMod_XXX in 1.89). (#4921, #456)
456
                            - ImGuiModFlags_Ctrl -> ImGuiMod_Ctrl, ImGuiModFlags_Shift -> ImGuiMod_Shift etc.
457
 - 2024/07/02 (1.91.0) - IO, IME: renamed platform IME hook and added explicit context for consistency and future-proofness.
458
                            - old: io.SetPlatformImeDataFn(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
459
                            - new: io.PlatformSetImeDataFn(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
460
 - 2024/06/21 (1.90.9) - BeginChild: added ImGuiChildFlags_NavFlattened as a replacement for the window flag ImGuiWindowFlags_NavFlattened: the feature only ever made sense for BeginChild() anyhow.
461
                            - old: BeginChild("Name", size, 0, ImGuiWindowFlags_NavFlattened);
462
                            - new: BeginChild("Name", size, ImGuiChildFlags_NavFlattened, 0);
463
 - 2024/06/21 (1.90.9) - io: ClearInputKeys() (first exposed in 1.89.8) doesn't clear mouse data, newly added ClearInputMouse() does.
464
 - 2024/06/20 (1.90.9) - renamed ImGuiDragDropFlags_SourceAutoExpirePayload to ImGuiDragDropFlags_PayloadAutoExpire.
465
 - 2024/06/18 (1.90.9) - style: renamed ImGuiCol_TabActive -> ImGuiCol_TabSelected, ImGuiCol_TabUnfocused -> ImGuiCol_TabDimmed, ImGuiCol_TabUnfocusedActive -> ImGuiCol_TabDimmedSelected.
466
 - 2024/06/10 (1.90.9) - removed old nested structure: renaming ImGuiStorage::ImGuiStoragePair type to ImGuiStoragePair (simpler for many languages).
467
 - 2024/06/06 (1.90.8) - reordered ImGuiInputTextFlags values. This should not be breaking unless you are using generated headers that have values not matching the main library.
468
 - 2024/06/06 (1.90.8) - removed 'ImGuiButtonFlags_MouseButtonDefault_ = ImGuiButtonFlags_MouseButtonLeft', was mostly unused and misleading.
469
 - 2024/05/27 (1.90.7) - commented out obsolete symbols marked obsolete in 1.88 (May 2022):
470
                            - old: CaptureKeyboardFromApp(bool)
471
                            - new: SetNextFrameWantCaptureKeyboard(bool)
472
                            - old: CaptureMouseFromApp(bool)
473
                            - new: SetNextFrameWantCaptureMouse(bool)
474
 - 2024/05/22 (1.90.7) - inputs (internals): renamed ImGuiKeyOwner_None to ImGuiKeyOwner_NoOwner, to make use more explicit and reduce confusion with the default it is a non-zero value and cannot be the default value (never made public, but disclosing as I expect a few users caught on owner-aware inputs).
475
                       - inputs (internals): renamed ImGuiInputFlags_RouteGlobalLow -> ImGuiInputFlags_RouteGlobal, ImGuiInputFlags_RouteGlobal -> ImGuiInputFlags_RouteGlobalOverFocused, ImGuiInputFlags_RouteGlobalHigh -> ImGuiInputFlags_RouteGlobalHighest.
476
                       - inputs (internals): Shortcut(), SetShortcutRouting(): swapped last two parameters order in function signatures:
477
                            - old: Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id = 0, ImGuiInputFlags flags = 0);
478
                            - new: Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags = 0, ImGuiID owner_id = 0);
479
                       - inputs (internals): owner-aware versions of IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(): swapped last two parameters order in function signatures.
480
                            - old: IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags = 0);
481
                            - new: IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id = 0);
482
                            - old: IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags = 0);
483
                            - new: IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id = 0);
484
                         for various reasons those changes makes sense. They are being made because making some of those API public.
485
                         only past users of imgui_internal.h with the extra parameters will be affected. Added asserts for valid flags in various functions to detect _some_ misuses, BUT NOT ALL.
486
 - 2024/05/21 (1.90.7) - docking: changed signature of DockSpaceOverViewport() to add explicit dockspace id if desired. pass 0 to use old behavior. (#7611)
487
                           - old: DockSpaceOverViewport(const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
488
                           - new: DockSpaceOverViewport(ImGuiID dockspace_id = 0, const ImGuiViewport* viewport = NULL, ImGuiDockNodeFlags flags = 0, ...);
489
 - 2024/05/16 (1.90.7) - inputs: on macOS X, Cmd and Ctrl keys are now automatically swapped by io.AddKeyEvent() as this naturally align with how macOS X uses those keys.
490
                           - it shouldn't really affect you unless you had custom shortcut swapping in place for macOS X apps.
491
                           - removed ImGuiMod_Shortcut which was previously dynamically remapping to Ctrl or Cmd/Super. It is now unnecessary to specific cross-platform idiomatic shortcuts. (#2343, #4084, #5923, #456)
492
 - 2024/05/14 (1.90.7) - backends: SDL_Renderer2 and SDL_Renderer3 backend now take a SDL_Renderer* in their RenderDrawData() functions.
493
 - 2024/04/18 (1.90.6) - TreeNode: Fixed a layout inconsistency when using an empty/hidden label followed by a SameLine() call. (#7505, #282)
494
                           - old: TreeNode("##Hidden"); SameLine(); Text("Hello");     // <-- This was actually incorrect! BUT appeared to look ok with the default style where ItemSpacing.x == FramePadding.x * 2 (it didn't look aligned otherwise).
495
                           - new: TreeNode("##Hidden"); SameLine(0, 0); Text("Hello"); // <-- This is correct for all styles values.
496
                         with the fix, IF you were successfully using TreeNode("")+SameLine(); you will now have extra spacing between your TreeNode and the following item.
497
                         You'll need to change the SameLine() call to SameLine(0,0) to remove this extraneous spacing. This seemed like the more sensible fix that's not making things less consistent.
498
                         (Note: when using this idiom you are likely to also use ImGuiTreeNodeFlags_SpanAvailWidth).
499
 - 2024/03/18 (1.90.5) - merged the radius_x/radius_y parameters in ImDrawList::AddEllipse(), AddEllipseFilled() and PathEllipticalArcTo() into a single ImVec2 parameter. Exceptionally, because those functions were added in 1.90, we are not adding inline redirection functions. The transition is easy and should affect few users. (#2743, #7417)
500
 - 2024/03/08 (1.90.5) - inputs: more formally obsoleted GetKeyIndex() when IMGUI_DISABLE_OBSOLETE_FUNCTIONS is set. It has been unnecessary and a no-op since 1.87 (it returns the same value as passed when used with a 1.87+ backend using io.AddKeyEvent() function). (#4921)
501
                           - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX)) -> use IsKeyPressed(ImGuiKey_XXX)
502
 - 2024/01/15 (1.90.2) - commented out obsolete ImGuiIO::ImeWindowHandle marked obsolete in 1.87, favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
503
 - 2023/12/19 (1.90.1) - commented out obsolete ImGuiKey_KeyPadEnter redirection to ImGuiKey_KeypadEnter.
504
 - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges.
505
 - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls.
506
 - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80.
507
 - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete).
508
 - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete).
509
                         those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features.
510
 - 2023/11/02 (1.90.0) - BeginChild: upgraded 'bool border = true' parameter to 'ImGuiChildFlags flags' type, added ImGuiChildFlags_Border equivalent. As with our prior "bool-to-flags" API updates, the ImGuiChildFlags_Border value is guaranteed to be == true forever to ensure a smoother transition, meaning all existing calls will still work.
511
                           - old: BeginChild("Name", size, true)
512
                           - new: BeginChild("Name", size, ImGuiChildFlags_Border)
513
                           - old: BeginChild("Name", size, false)
514
                           - new: BeginChild("Name", size) or BeginChild("Name", 0) or BeginChild("Name", size, ImGuiChildFlags_None)
515
 - 2023/11/02 (1.90.0) - BeginChild: added child-flag ImGuiChildFlags_AlwaysUseWindowPadding as a replacement for the window-flag ImGuiWindowFlags_AlwaysUseWindowPadding: the feature only ever made sense for BeginChild() anyhow.
516
                           - old: BeginChild("Name", size, 0, ImGuiWindowFlags_AlwaysUseWindowPadding);
517
                           - new: BeginChild("Name", size, ImGuiChildFlags_AlwaysUseWindowPadding, 0);
518
 - 2023/09/27 (1.90.0) - io: removed io.MetricsActiveAllocations introduced in 1.63. Same as 'g.DebugMemAllocCount - g.DebugMemFreeCount' (still displayed in Metrics, unlikely to be accessed by end-user).
519
 - 2023/09/26 (1.90.0) - debug tools: Renamed ShowStackToolWindow() ("Stack Tool") to ShowIDStackToolWindow() ("ID Stack Tool"), as earlier name was misleading. Kept inline redirection function. (#4631)
520
 - 2023/09/15 (1.90.0) - ListBox, Combo: changed signature of "name getter" callback in old one-liner ListBox()/Combo() apis. kept inline redirection function (will obsolete).
521
                           - old: bool Combo(const char* label, int* current_item, bool (*getter)(void* user_data, int idx, const char** out_text), ...)
522
                           - new: bool Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
523
                           - old: bool ListBox(const char* label, int* current_item, bool (*getting)(void* user_data, int idx, const char** out_text), ...);
524
                           - new: bool ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), ...);
525
 - 2023/09/08 (1.90.0) - commented out obsolete redirecting functions:
526
                           - GetWindowContentRegionWidth()  -> use GetWindowContentRegionMax().x - GetWindowContentRegionMin().x. Consider that generally 'GetContentRegionAvail().x' is more useful.
527
                           - ImDrawCornerFlags_XXX          -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details + grep commented names in sources.
528
                       - commented out runtime support for hardcoded ~0 or 0x01..0x0F rounding flags values for AddRect()/AddRectFilled()/PathRect()/AddImageRounded() -> use ImDrawFlags_RoundCornersXXX flags. Read 1.82 Changelog for details
529
 - 2023/08/25 (1.89.9) - clipper: Renamed IncludeRangeByIndices() (also called ForceDisplayRangeByIndices() before 1.89.6) to IncludeItemsByIndex(). Kept inline redirection function. Sorry!
530
 - 2023/07/12 (1.89.8) - ImDrawData: CmdLists now owned, changed from ImDrawList** to ImVector<ImDrawList*>. Majority of users shouldn't be affected, but you cannot compare to NULL nor reassign manually anymore. Instead use AddDrawList(). (#6406, #4879, #1878)
531
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
532
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
533
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
534
 - 2023/06/28 (1.89.7) - overlapping items: Selectable and TreeNode don't allow overlap when active so overlapping widgets won't appear as hovered. While this fixes a common small visual issue, it also means that calling IsItemHovered() after a non-reactive elements - e.g. Text() - overlapping an active one may fail if you don't use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem). (#6610)
535
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
536
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
537
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
538
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
539
                           - ListBoxFooter()  -> use EndListBox()
540
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
541
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
542
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
543
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
544
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
545
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
546
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
547
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
548
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
549
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
550
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
551
                         it has been frequently requested by people to use our own. We had an opt-in define which was
552
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
553
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
554
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
555
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
556
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
557
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
558
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
559
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
560
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
561
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
562
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
563
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
564
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
565
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
566
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
567
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
568
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
569
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
570
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
571
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
572
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
573
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
574
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
575
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
576
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
577
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
578
                         - previously this would make the window content size ~200x200:
579
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
580
                         - instead, please submit an item:
581
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
582
                         - alternative:
583
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
584
                         - content size is now only extended when submitting an item!
585
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
586
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
587
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
588
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
589
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
590
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
591
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
592
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
593
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
594
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
595
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
596
                        - Official backends from 1.87+                  -> no issue.
597
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
598
                        - Custom backends not writing to io.NavInputs[] -> no issue.
599
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
600
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
601
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
602
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
603
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
604
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
605
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
606
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
607
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
608
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
609
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
610
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
611
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
612
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
613
                       read https://github.com/ocornut/imgui/issues/4921 for details.
614
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unnecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
615
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
616
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
617
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
618
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
619
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
620
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
621
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
622
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
623
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
624
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
625
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
626
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
627
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
628
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
629
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
630
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
631
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
632
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
633
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
634
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
635
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
636
                        - if you are using official backends from the source tree: you have nothing to do.
637
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
638
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
639
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
640
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
641
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
642
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
643
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
644
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
645
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
646
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
647
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
648
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
649
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
650
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
651
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
652
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
653
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
654
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
655
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
656
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
657
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
658
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
659
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
660
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
661
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
662
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
663
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
664
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
665
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
666
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
667
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
668
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
669
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
670
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
671
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
672
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
673
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
674
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
675
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
676
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
677
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
678
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
679
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
680
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
681
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
682
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
683
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
684
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
685
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
686
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
687
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
688
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
689
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
690
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
691
                       - if you omitted the 'power' parameter (likely!), you are not affected.
692
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
693
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
694
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
695
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
696
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
697
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
698
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
699
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
700
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
701
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
702
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
703
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
704
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
705
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
706
                       - ShowTestWindow()                    -> use ShowDemoWindow()
707
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
708
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
709
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
710
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
711
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
712
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
713
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
714
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
715
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
716
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
717
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
718
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
719
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
720
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
721
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
722
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
723
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
724
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
725
                       - ImFont::Glyph                       -> use ImFontGlyph
726
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
727
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
728
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
729
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
730
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
731
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
732
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
733
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
734
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
735
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
736
                       Please reach out if you are affected.
737
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
738
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
739
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
740
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
741
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
742
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
743
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
744
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
745
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
746
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
747
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
748
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
749
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
750
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
751
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
752
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
753
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
754
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
755
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
756
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
757
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
758
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
759
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
760
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
761
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
762
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
763
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
764
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
765
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
766
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
767
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
768
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
769
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
770
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
771
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
772
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
773
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
774
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
775
                       consistent with other functions. Kept redirection functions (will obsolete).
776
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
777
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
778
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
779
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
780
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
781
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
782
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
783
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
784
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
785
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
786
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
787
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
788
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
789
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
790
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
791
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
792
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
793
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
794
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
795
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
796
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
797
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
798
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
799
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
800
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
801
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
802
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
803
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
804
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
805
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
806
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
807
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
808
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
809
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
810
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
811
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
812
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
813
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
814
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
815
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
816
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
817
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
818
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
819
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
820
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
821
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
822
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
823
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
824
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
825
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
826
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
827
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
828
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
829
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
830
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
831
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
832
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
833
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
834
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
835
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
836
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
837
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
838
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
839
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
840
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
841
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
842
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
843
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
844
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
845
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
846
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
847
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
848
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
849
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
850
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
851
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
852
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
853
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
854
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
855
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
856
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
857
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
858
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
859
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
860
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
861
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
862
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
863
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
864
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
865
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
866
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
867
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
868
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
869
                     - the signature of the io.RenderDrawListsFn handler has changed!
870
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
871
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
872
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
873
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
874
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
875
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
876
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
877
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
878
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
879
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
880
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
881
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
882
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
883
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
884
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
885
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
886
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
887
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
888
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
889
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
890
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
891
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
892
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
893
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
894
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
895
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
896
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
897
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
898
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
899
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
900
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
901
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
902
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
903
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
904
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
905
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
906
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
907
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
908
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
909
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
910
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
911
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
912
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
913
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
914
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
915
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
916
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
917
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
918
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
919
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
920
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
921
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
922
923
924
 FREQUENTLY ASKED QUESTIONS (FAQ)
925
 ================================
926
927
 Read all answers online:
928
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
929
 Read all answers locally (with a text editor or ideally a Markdown viewer):
930
   docs/FAQ.md
931
 Some answers are copied down here to facilitate searching in code.
932
933
 Q&A: Basics
934
 ===========
935
936
 Q: Where is the documentation?
937
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
938
    - Run the examples/ applications and explore them.
939
    - Read Getting Started (https://github.com/ocornut/imgui/wiki/Getting-Started) guide.
940
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
941
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
942
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
943
    - 20+ standalone example applications using e.g. OpenGL/DirectX are provided in the
944
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
945
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
946
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
947
    - Your programming IDE is your friend, find the type or function declaration to find comments
948
      associated with it.
949
950
 Q: What is this library called?
951
 Q: Which version should I get?
952
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
953
 >> See https://www.dearimgui.com/faq for details.
954
955
 Q&A: Integration
956
 ================
957
958
 Q: How to get started?
959
 A: Read https://github.com/ocornut/imgui/wiki/Getting-Started. Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
960
961
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
962
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
963
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
964
965
 Q. How can I enable keyboard or gamepad controls?
966
 Q: How can I use this on a machine without mouse, keyboard or screen? (input share, remote display)
967
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
968
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
969
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
970
 >> See https://www.dearimgui.com/faq
971
972
 Q&A: Usage
973
 ----------
974
975
 Q: About the ID Stack system..
976
   - Why is my widget not reacting when I click on it?
977
   - How can I have widgets with an empty label?
978
   - How can I have multiple widgets with the same label?
979
   - How can I have multiple windows with the same label?
980
 Q: How can I display an image? What is ImTextureID, how does it work?
981
 Q: How can I use my own math types instead of ImVec2?
982
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
983
 Q: How can I display custom shapes? (using low-level ImDrawList API)
984
 >> See https://www.dearimgui.com/faq
985
986
 Q&A: Fonts, Text
987
 ================
988
989
 Q: How should I handle DPI in my application?
990
 Q: How can I load a different font than the default?
991
 Q: How can I easily use icons in my application?
992
 Q: How can I load multiple fonts?
993
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
994
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/blob/master/docs/FONTS.md
995
996
 Q&A: Concerns
997
 =============
998
999
 Q: Who uses Dear ImGui?
1000
 Q: Can you create elaborate/serious tools with Dear ImGui?
1001
 Q: Can you reskin the look of Dear ImGui?
1002
 Q: Why using C++ (as opposed to C)?
1003
 >> See https://www.dearimgui.com/faq
1004
1005
 Q&A: Community
1006
 ==============
1007
1008
 Q: How can I help?
1009
 A: - Businesses: please reach out to "omar AT dearimgui DOT com" if you work in a place using Dear ImGui!
1010
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
1011
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we sustain and grow work on this project.
1012
      >>> See https://github.com/ocornut/imgui/wiki/Funding
1013
    - Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine.
1014
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, and see how you want to help and can help!
1015
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
1016
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
1017
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
1018
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
1019
1020
*/
1021
1022
//-------------------------------------------------------------------------
1023
// [SECTION] INCLUDES
1024
//-------------------------------------------------------------------------
1025
1026
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
1027
#define _CRT_SECURE_NO_WARNINGS
1028
#endif
1029
1030
#ifndef IMGUI_DEFINE_MATH_OPERATORS
1031
#define IMGUI_DEFINE_MATH_OPERATORS
1032
#endif
1033
1034
#include "imgui.h"
1035
#ifndef IMGUI_DISABLE
1036
#include "imgui_internal.h"
1037
1038
// System includes
1039
#include <stdio.h>      // vsnprintf, sscanf, printf
1040
#include <stdint.h>     // intptr_t
1041
1042
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
1043
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
1044
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1045
#endif
1046
1047
// [Windows] OS specific includes (optional)
1048
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && defined(IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1049
#define IMGUI_DISABLE_WIN32_FUNCTIONS
1050
#endif
1051
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
1052
#ifndef WIN32_LEAN_AND_MEAN
1053
#define WIN32_LEAN_AND_MEAN
1054
#endif
1055
#ifndef NOMINMAX
1056
#define NOMINMAX
1057
#endif
1058
#ifndef __MINGW32__
1059
#include <Windows.h>        // _wfopen, OpenClipboard
1060
#else
1061
#include <windows.h>
1062
#endif
1063
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP || WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
1064
// The UWP and GDK Win32 API subsets don't support clipboard nor IME functions
1065
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
1066
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
1067
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
1068
#endif
1069
#endif
1070
1071
// [Apple] OS specific includes
1072
#if defined(__APPLE__)
1073
#include <TargetConditionals.h>
1074
#endif
1075
1076
// Visual Studio warnings
1077
#ifdef _MSC_VER
1078
#pragma warning (disable: 4127)             // condition expression is constant
1079
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
1080
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
1081
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
1082
#endif
1083
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
1084
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
1085
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
1086
#endif
1087
1088
// Clang/GCC warnings with -Weverything
1089
#if defined(__clang__)
1090
#if __has_warning("-Wunknown-warning-option")
1091
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
1092
#endif
1093
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
1094
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
1095
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
1096
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
1097
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
1098
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
1099
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
1100
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
1101
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
1102
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
1103
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
1104
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
1105
#pragma clang diagnostic ignored "-Wunsafe-buffer-usage"            // warning: 'xxx' is an unsafe pointer used for buffer access
1106
#elif defined(__GNUC__)
1107
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
1108
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
1109
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
1110
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
1111
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
1112
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
1113
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
1114
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
1115
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
1116
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
1117
#endif
1118
1119
// Debug options
1120
182k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Hold CTRL to display for all candidates. CTRL+Arrow to change last direction.
1121
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1122
1123
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1124
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1125
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1126
1127
static const float NAV_ACTIVATE_HIGHLIGHT_TIMER             = 0.10f;    // Time to highlight an item activated by a shortcut.
1128
1129
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1130
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1131
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1132
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1133
1134
// Tooltip offset
1135
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1136
1137
// Docking
1138
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1139
1140
//-------------------------------------------------------------------------
1141
// [SECTION] FORWARD DECLARATIONS
1142
//-------------------------------------------------------------------------
1143
1144
static void             SetCurrentWindow(ImGuiWindow* window);
1145
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1146
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1147
1148
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1149
1150
// Settings
1151
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1152
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1153
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1154
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1155
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1156
1157
// Platform Dependents default implementation for IO functions
1158
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1159
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1160
static void             PlatformSetImeDataFn_DefaultImpl(ImGuiContext* ctx, ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1161
static bool             PlatformOpenInShellFn_DefaultImpl(ImGuiContext* ctx, const char* path);
1162
1163
namespace ImGui
1164
{
1165
// Item
1166
static void             ItemHandleShortcut(ImGuiID id);
1167
1168
// Navigation
1169
static void             NavUpdate();
1170
static void             NavUpdateWindowing();
1171
static void             NavUpdateWindowingOverlay();
1172
static void             NavUpdateCancelRequest();
1173
static void             NavUpdateCreateMoveRequest();
1174
static void             NavUpdateCreateTabbingRequest();
1175
static float            NavUpdatePageUpPageDown();
1176
static inline void      NavUpdateAnyRequestFlag();
1177
static void             NavUpdateCreateWrappingRequest();
1178
static void             NavEndFrame();
1179
static bool             NavScoreItem(ImGuiNavItemData* result);
1180
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1181
static void             NavProcessItem();
1182
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1183
static ImVec2           NavCalcPreferredRefPos();
1184
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1185
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1186
static void             NavRestoreLayer(ImGuiNavLayer layer);
1187
static int              FindWindowFocusIndex(ImGuiWindow* window);
1188
1189
// Error Checking and Debug Tools
1190
static void             ErrorCheckNewFrameSanityChecks();
1191
static void             ErrorCheckEndFrameSanityChecks();
1192
static void             UpdateDebugToolItemPicker();
1193
static void             UpdateDebugToolStackQueries();
1194
static void             UpdateDebugToolFlashStyleColor();
1195
1196
// Inputs
1197
static void             UpdateKeyboardInputs();
1198
static void             UpdateMouseInputs();
1199
static void             UpdateMouseWheel();
1200
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1201
1202
// Misc
1203
static void             UpdateSettings();
1204
static int              UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1205
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1206
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1207
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1208
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1209
static void             RenderDimmedBackgrounds();
1210
static void             SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect);
1211
1212
// Viewports
1213
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1214
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1215
static void             DestroyViewport(ImGuiViewportP* viewport);
1216
static void             UpdateViewportsNewFrame();
1217
static void             UpdateViewportsEndFrame();
1218
static void             WindowSelectViewport(ImGuiWindow* window);
1219
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1220
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1221
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1222
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1223
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1224
static int              FindPlatformMonitorForRect(const ImRect& r);
1225
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1226
1227
}
1228
1229
//-----------------------------------------------------------------------------
1230
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1231
//-----------------------------------------------------------------------------
1232
1233
// DLL users:
1234
// - Heaps and globals are not shared across DLL boundaries!
1235
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1236
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1237
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1238
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1239
1240
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1241
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1242
//   Change to a different context by calling ImGui::SetCurrentContext().
1243
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1244
//   If you want thread-safety to allow N threads to access N different contexts:
1245
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1246
//         struct ImGuiContext;
1247
//         extern thread_local ImGuiContext* MyImGuiTLS;
1248
//         #define GImGui MyImGuiTLS
1249
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1250
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1251
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1252
// - DLL users: read comments above.
1253
#ifndef GImGui
1254
ImGuiContext*   GImGui = NULL;
1255
#endif
1256
1257
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1258
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1259
// - DLL users: read comments above.
1260
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1261
1.25k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1262
1.20k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1263
#else
1264
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1265
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1266
#endif
1267
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1268
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1269
static void*                GImAllocatorUserData = NULL;
1270
1271
//-----------------------------------------------------------------------------
1272
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1273
//-----------------------------------------------------------------------------
1274
1275
ImGuiStyle::ImGuiStyle()
1276
1
{
1277
1
    Alpha                       = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1278
1
    DisabledAlpha               = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1279
1
    WindowPadding               = ImVec2(8,8);      // Padding within a window
1280
1
    WindowRounding              = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1281
1
    WindowBorderSize            = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1282
1
    WindowMinSize               = ImVec2(32,32);    // Minimum window size
1283
1
    WindowTitleAlign            = ImVec2(0.0f,0.5f);// Alignment for title bar text
1284
1
    WindowMenuButtonPosition    = ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1285
1
    ChildRounding               = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1286
1
    ChildBorderSize             = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1287
1
    PopupRounding               = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1288
1
    PopupBorderSize             = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1289
1
    FramePadding                = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1290
1
    FrameRounding               = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1291
1
    FrameBorderSize             = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1292
1
    ItemSpacing                 = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1293
1
    ItemInnerSpacing            = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1294
1
    CellPadding                 = ImVec2(4,2);      // Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows.
1295
1
    TouchExtraPadding           = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1296
1
    IndentSpacing               = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1297
1
    ColumnsMinSpacing           = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1298
1
    ScrollbarSize               = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1299
1
    ScrollbarRounding           = 9.0f;             // Radius of grab corners rounding for scrollbar
1300
1
    GrabMinSize                 = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1301
1
    GrabRounding                = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1302
1
    LogSliderDeadzone           = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1303
1
    TabRounding                 = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1304
1
    TabBorderSize               = 0.0f;             // Thickness of border around tabs.
1305
1
    TabMinWidthForCloseButton   = 0.0f;             // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1306
1
    TabBarBorderSize            = 1.0f;             // Thickness of tab-bar separator, which takes on the tab active color to denote focus.
1307
1
    TabBarOverlineSize          = 2.0f;             // Thickness of tab-bar overline, which highlights the selected tab-bar.
1308
1
    TableAngledHeadersAngle     = 35.0f * (IM_PI / 180.0f); // Angle of angled headers (supported values range from -50 degrees to +50 degrees).
1309
1
    TableAngledHeadersTextAlign = ImVec2(0.5f,0.0f);// Alignment of angled headers within the cell
1310
1
    ColorButtonPosition         = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1311
1
    ButtonTextAlign             = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1312
1
    SelectableTextAlign         = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1313
1
    SeparatorTextBorderSize     = 3.0f;             // Thickness of border in SeparatorText()
1314
1
    SeparatorTextAlign          = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1315
1
    SeparatorTextPadding        = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1316
1
    DisplayWindowPadding        = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1317
1
    DisplaySafeAreaPadding      = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1318
1
    DockingSeparatorSize        = 2.0f;             // Thickness of resizing border between docked windows
1319
1
    MouseCursorScale            = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1320
1
    AntiAliasedLines            = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1321
1
    AntiAliasedLinesUseTex      = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1322
1
    AntiAliasedFill             = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1323
1
    CurveTessellationTol        = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1324
1
    CircleTessellationMaxError  = 0.30f;            // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1325
1326
    // Behaviors
1327
1
    HoverStationaryDelay        = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1328
1
    HoverDelayShort             = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1329
1
    HoverDelayNormal            = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1330
1
    HoverFlagsForTooltipMouse   = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_AllowWhenDisabled;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1331
1
    HoverFlagsForTooltipNav     = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal | ImGuiHoveredFlags_AllowWhenDisabled;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1332
1333
    // Default theme
1334
1
    ImGui::StyleColorsDark(this);
1335
1
}
1336
1337
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1338
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1339
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1340
0
{
1341
0
    WindowPadding = ImTrunc(WindowPadding * scale_factor);
1342
0
    WindowRounding = ImTrunc(WindowRounding * scale_factor);
1343
0
    WindowMinSize = ImTrunc(WindowMinSize * scale_factor);
1344
0
    ChildRounding = ImTrunc(ChildRounding * scale_factor);
1345
0
    PopupRounding = ImTrunc(PopupRounding * scale_factor);
1346
0
    FramePadding = ImTrunc(FramePadding * scale_factor);
1347
0
    FrameRounding = ImTrunc(FrameRounding * scale_factor);
1348
0
    ItemSpacing = ImTrunc(ItemSpacing * scale_factor);
1349
0
    ItemInnerSpacing = ImTrunc(ItemInnerSpacing * scale_factor);
1350
0
    CellPadding = ImTrunc(CellPadding * scale_factor);
1351
0
    TouchExtraPadding = ImTrunc(TouchExtraPadding * scale_factor);
1352
0
    IndentSpacing = ImTrunc(IndentSpacing * scale_factor);
1353
0
    ColumnsMinSpacing = ImTrunc(ColumnsMinSpacing * scale_factor);
1354
0
    ScrollbarSize = ImTrunc(ScrollbarSize * scale_factor);
1355
0
    ScrollbarRounding = ImTrunc(ScrollbarRounding * scale_factor);
1356
0
    GrabMinSize = ImTrunc(GrabMinSize * scale_factor);
1357
0
    GrabRounding = ImTrunc(GrabRounding * scale_factor);
1358
0
    LogSliderDeadzone = ImTrunc(LogSliderDeadzone * scale_factor);
1359
0
    TabRounding = ImTrunc(TabRounding * scale_factor);
1360
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImTrunc(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1361
0
    TabBarOverlineSize = ImTrunc(TabBarOverlineSize * scale_factor);
1362
0
    SeparatorTextPadding = ImTrunc(SeparatorTextPadding * scale_factor);
1363
0
    DockingSeparatorSize = ImTrunc(DockingSeparatorSize * scale_factor);
1364
0
    DisplayWindowPadding = ImTrunc(DisplayWindowPadding * scale_factor);
1365
0
    DisplaySafeAreaPadding = ImTrunc(DisplaySafeAreaPadding * scale_factor);
1366
0
    MouseCursorScale = ImTrunc(MouseCursorScale * scale_factor);
1367
0
}
1368
1369
ImGuiIO::ImGuiIO()
1370
1
{
1371
    // Most fields are initialized with zero
1372
1
    memset(this, 0, sizeof(*this));
1373
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1374
1375
    // Settings
1376
1
    ConfigFlags = ImGuiConfigFlags_None;
1377
1
    BackendFlags = ImGuiBackendFlags_None;
1378
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1379
1
    DeltaTime = 1.0f / 60.0f;
1380
1
    IniSavingRate = 5.0f;
1381
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1382
1
    LogFilename = "imgui_log.txt";
1383
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1384
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1385
        KeyMap[i] = -1;
1386
#endif
1387
1
    UserData = NULL;
1388
1389
1
    Fonts = NULL;
1390
1
    FontGlobalScale = 1.0f;
1391
1
    FontDefault = NULL;
1392
1
    FontAllowUserScaling = false;
1393
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1394
1395
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1396
1
    ConfigDockingNoSplit = false;
1397
1
    ConfigDockingWithShift = false;
1398
1
    ConfigDockingAlwaysTabBar = false;
1399
1
    ConfigDockingTransparentPayload = false;
1400
1401
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1402
1
    ConfigViewportsNoAutoMerge = false;
1403
1
    ConfigViewportsNoTaskBarIcon = false;
1404
1
    ConfigViewportsNoDecoration = true;
1405
1
    ConfigViewportsNoDefaultParent = false;
1406
1407
    // Miscellaneous options
1408
1
    MouseDrawCursor = false;
1409
#ifdef __APPLE__
1410
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1411
#else
1412
1
    ConfigMacOSXBehaviors = false;
1413
1
#endif
1414
1
    ConfigNavSwapGamepadButtons = false;
1415
1
    ConfigInputTrickleEventQueue = true;
1416
1
    ConfigInputTextCursorBlink = true;
1417
1
    ConfigInputTextEnterKeepActive = false;
1418
1
    ConfigDragClickToInputText = false;
1419
1
    ConfigWindowsResizeFromEdges = true;
1420
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1421
1
    ConfigMemoryCompactTimer = 60.0f;
1422
1
    ConfigDebugBeginReturnValueOnce = false;
1423
1
    ConfigDebugBeginReturnValueLoop = false;
1424
1425
    // Inputs Behaviors
1426
1
    MouseDoubleClickTime = 0.30f;
1427
1
    MouseDoubleClickMaxDist = 6.0f;
1428
1
    MouseDragThreshold = 6.0f;
1429
1
    KeyRepeatDelay = 0.275f;
1430
1
    KeyRepeatRate = 0.050f;
1431
1432
    // Platform Functions
1433
    // Note: Initialize() will setup default clipboard/ime handlers.
1434
1
    BackendPlatformName = BackendRendererName = NULL;
1435
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1436
1
    PlatformOpenInShellUserData = NULL;
1437
1
    PlatformLocaleDecimalPoint = '.';
1438
1439
    // Input (NB: we already have memset zero the entire structure!)
1440
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1441
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1442
1
    MouseSource = ImGuiMouseSource_Mouse;
1443
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1444
155
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1445
1
    AppAcceptingEvents = true;
1446
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1447
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1448
1
}
1449
1450
// Pass in translated ASCII characters for text input.
1451
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1452
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1453
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1454
void ImGuiIO::AddInputCharacter(unsigned int c)
1455
6.43k
{
1456
6.43k
    IM_ASSERT(Ctx != NULL);
1457
6.43k
    ImGuiContext& g = *Ctx;
1458
6.43k
    if (c == 0 || !AppAcceptingEvents)
1459
1.71k
        return;
1460
1461
4.72k
    ImGuiInputEvent e;
1462
4.72k
    e.Type = ImGuiInputEventType_Text;
1463
4.72k
    e.Source = ImGuiInputSource_Keyboard;
1464
4.72k
    e.EventId = g.InputEventsNextEventId++;
1465
4.72k
    e.Text.Char = c;
1466
4.72k
    g.InputEventsQueue.push_back(e);
1467
4.72k
}
1468
1469
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1470
// we should save the high surrogate.
1471
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1472
4.24k
{
1473
4.24k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1474
599
        return;
1475
1476
3.64k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1477
1.58k
    {
1478
1.58k
        if (InputQueueSurrogate != 0)
1479
525
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1480
1.58k
        InputQueueSurrogate = c;
1481
1.58k
        return;
1482
1.58k
    }
1483
1484
2.06k
    ImWchar cp = c;
1485
2.06k
    if (InputQueueSurrogate != 0)
1486
1.00k
    {
1487
1.00k
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1488
511
        {
1489
511
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1490
511
        }
1491
495
        else
1492
495
        {
1493
495
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1494
495
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1495
#else
1496
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1497
#endif
1498
495
        }
1499
1500
1.00k
        InputQueueSurrogate = 0;
1501
1.00k
    }
1502
2.06k
    AddInputCharacter((unsigned)cp);
1503
2.06k
}
1504
1505
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1506
69
{
1507
69
    if (!AppAcceptingEvents)
1508
0
        return;
1509
69
    while (*utf8_chars != 0)
1510
0
    {
1511
0
        unsigned int c = 0;
1512
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1513
0
        AddInputCharacter(c);
1514
0
    }
1515
69
}
1516
1517
// Clear all incoming events.
1518
void ImGuiIO::ClearEventsQueue()
1519
0
{
1520
0
    IM_ASSERT(Ctx != NULL);
1521
0
    ImGuiContext& g = *Ctx;
1522
0
    g.InputEventsQueue.clear();
1523
0
}
1524
1525
// Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons.
1526
void ImGuiIO::ClearInputKeys()
1527
11.7k
{
1528
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1529
    memset(KeysDown, 0, sizeof(KeysDown));
1530
#endif
1531
1.81M
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1532
1.80M
    {
1533
1.80M
        if (ImGui::IsMouseKey((ImGuiKey)(n + ImGuiKey_KeysData_OFFSET)))
1534
81.9k
            continue;
1535
1.72M
        KeysData[n].Down             = false;
1536
1.72M
        KeysData[n].DownDuration     = -1.0f;
1537
1.72M
        KeysData[n].DownDurationPrev = -1.0f;
1538
1.72M
    }
1539
11.7k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1540
11.7k
    KeyMods = ImGuiMod_None;
1541
11.7k
    InputQueueCharacters.resize(0); // Behavior of old ClearInputCharacters().
1542
11.7k
}
1543
1544
void ImGuiIO::ClearInputMouse()
1545
2.00k
{
1546
16.0k
    for (ImGuiKey key = ImGuiKey_Mouse_BEGIN; key < ImGuiKey_Mouse_END; key = (ImGuiKey)(key + 1))
1547
14.0k
    {
1548
14.0k
        ImGuiKeyData* key_data = &KeysData[key - ImGuiKey_KeysData_OFFSET];
1549
14.0k
        key_data->Down = false;
1550
14.0k
        key_data->DownDuration = -1.0f;
1551
14.0k
        key_data->DownDurationPrev = -1.0f;
1552
14.0k
    }
1553
2.00k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1554
12.0k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1555
10.0k
    {
1556
10.0k
        MouseDown[n] = false;
1557
10.0k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1558
10.0k
    }
1559
2.00k
    MouseWheel = MouseWheelH = 0.0f;
1560
2.00k
}
1561
1562
// Removed this as it is ambiguous/misleading and generally incorrect to use with the existence of a higher-level input queue.
1563
// Current frame character buffer is now also cleared by ClearInputKeys().
1564
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1565
void ImGuiIO::ClearInputCharacters()
1566
{
1567
    InputQueueCharacters.resize(0);
1568
}
1569
#endif
1570
1571
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1572
36.0k
{
1573
36.0k
    ImGuiContext& g = *ctx;
1574
69.0k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1575
49.7k
    {
1576
49.7k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1577
49.7k
        if (e->Type != type)
1578
18.9k
            continue;
1579
30.7k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1580
9.24k
            continue;
1581
21.5k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1582
4.72k
            continue;
1583
16.8k
        return e;
1584
21.5k
    }
1585
19.2k
    return NULL;
1586
36.0k
}
1587
1588
// Queue a new key down/up event.
1589
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1590
// - bool down:          Is the key down? use false to signify a key release.
1591
// - float analog_value: 0.0f..1.0f
1592
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1593
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1594
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1595
12.1k
{
1596
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1597
12.1k
    IM_ASSERT(Ctx != NULL);
1598
12.1k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1599
0
        return;
1600
12.1k
    ImGuiContext& g = *Ctx;
1601
12.1k
    IM_ASSERT(ImGui::IsNamedKeyOrMod(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1602
12.1k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1603
1604
    // MacOS: swap Cmd(Super) and Ctrl
1605
12.1k
    if (g.IO.ConfigMacOSXBehaviors)
1606
0
    {
1607
0
        if (key == ImGuiMod_Super)          { key = ImGuiMod_Ctrl; }
1608
0
        else if (key == ImGuiMod_Ctrl)      { key = ImGuiMod_Super; }
1609
0
        else if (key == ImGuiKey_LeftSuper) { key = ImGuiKey_LeftCtrl; }
1610
0
        else if (key == ImGuiKey_RightSuper){ key = ImGuiKey_RightCtrl; }
1611
0
        else if (key == ImGuiKey_LeftCtrl)  { key = ImGuiKey_LeftSuper; }
1612
0
        else if (key == ImGuiKey_RightCtrl) { key = ImGuiKey_RightSuper; }
1613
0
    }
1614
1615
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1616
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1617
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1618
    if (BackendUsingLegacyKeyArrays == -1)
1619
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1620
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1621
    BackendUsingLegacyKeyArrays = 0;
1622
#endif
1623
12.1k
    if (ImGui::IsGamepadKey(key))
1624
175
        BackendUsingLegacyNavInputArray = false;
1625
1626
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1627
12.1k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1628
12.1k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1629
12.1k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1630
12.1k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1631
12.1k
    if (latest_key_down == down && latest_key_analog == analog_value)
1632
1.17k
        return;
1633
1634
    // Add event
1635
10.9k
    ImGuiInputEvent e;
1636
10.9k
    e.Type = ImGuiInputEventType_Key;
1637
10.9k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1638
10.9k
    e.EventId = g.InputEventsNextEventId++;
1639
10.9k
    e.Key.Key = key;
1640
10.9k
    e.Key.Down = down;
1641
10.9k
    e.Key.AnalogValue = analog_value;
1642
10.9k
    g.InputEventsQueue.push_back(e);
1643
10.9k
}
1644
1645
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1646
1.07k
{
1647
1.07k
    if (!AppAcceptingEvents)
1648
0
        return;
1649
1.07k
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1650
1.07k
}
1651
1652
// [Optional] Call after AddKeyEvent().
1653
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1654
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1655
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1656
0
{
1657
0
    if (key == ImGuiKey_None)
1658
0
        return;
1659
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1660
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1661
0
    IM_UNUSED(native_keycode);  // Yet unused
1662
0
    IM_UNUSED(native_scancode); // Yet unused
1663
1664
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1665
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1666
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1667
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1668
        return;
1669
    KeyMap[legacy_key] = key;
1670
    KeyMap[key] = legacy_key;
1671
#else
1672
0
    IM_UNUSED(key);
1673
0
    IM_UNUSED(native_legacy_index);
1674
0
#endif
1675
0
}
1676
1677
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1678
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1679
0
{
1680
0
    AppAcceptingEvents = accepting_events;
1681
0
}
1682
1683
// Queue a mouse move event
1684
void ImGuiIO::AddMousePosEvent(float x, float y)
1685
7.94k
{
1686
7.94k
    IM_ASSERT(Ctx != NULL);
1687
7.94k
    ImGuiContext& g = *Ctx;
1688
7.94k
    if (!AppAcceptingEvents)
1689
0
        return;
1690
1691
    // Apply same flooring as UpdateMouseInputs()
1692
7.94k
    ImVec2 pos((x > -FLT_MAX) ? ImFloor(x) : x, (y > -FLT_MAX) ? ImFloor(y) : y);
1693
1694
    // Filter duplicate
1695
7.94k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1696
7.94k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1697
7.94k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1698
1.82k
        return;
1699
1700
6.11k
    ImGuiInputEvent e;
1701
6.11k
    e.Type = ImGuiInputEventType_MousePos;
1702
6.11k
    e.Source = ImGuiInputSource_Mouse;
1703
6.11k
    e.EventId = g.InputEventsNextEventId++;
1704
6.11k
    e.MousePos.PosX = pos.x;
1705
6.11k
    e.MousePos.PosY = pos.y;
1706
6.11k
    e.MousePos.MouseSource = g.InputEventsNextMouseSource;
1707
6.11k
    g.InputEventsQueue.push_back(e);
1708
6.11k
}
1709
1710
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1711
13.5k
{
1712
13.5k
    IM_ASSERT(Ctx != NULL);
1713
13.5k
    ImGuiContext& g = *Ctx;
1714
13.5k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1715
13.5k
    if (!AppAcceptingEvents)
1716
0
        return;
1717
1718
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click: handle held button.
1719
13.5k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && MouseCtrlLeftAsRightClick)
1720
0
    {
1721
        // Order of both statements matterns: this event will still release mouse button 1
1722
0
        mouse_button = 1;
1723
0
        if (!down)
1724
0
            MouseCtrlLeftAsRightClick = false;
1725
0
    }
1726
1727
    // Filter duplicate
1728
13.5k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1729
13.5k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1730
13.5k
    if (latest_button_down == down)
1731
3.08k
        return;
1732
1733
    // On MacOS X: Convert Ctrl(Super)+Left click into Right-click.
1734
    // - Note that this is actual physical Ctrl which is ImGuiMod_Super for us.
1735
    // - At this point we want from !down to down, so this is handling the initial press.
1736
10.4k
    if (ConfigMacOSXBehaviors && mouse_button == 0 && down)
1737
0
    {
1738
0
        const ImGuiInputEvent* latest_super_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)ImGuiMod_Super);
1739
0
        if (latest_super_event ? latest_super_event->Key.Down : g.IO.KeySuper)
1740
0
        {
1741
0
            IMGUI_DEBUG_LOG_IO("[io] Super+Left Click aliased into Right Click\n");
1742
0
            MouseCtrlLeftAsRightClick = true;
1743
0
            AddMouseButtonEvent(1, true); // This is just quicker to write that passing through, as we need to filter duplicate again.
1744
0
            return;
1745
0
        }
1746
0
    }
1747
1748
10.4k
    ImGuiInputEvent e;
1749
10.4k
    e.Type = ImGuiInputEventType_MouseButton;
1750
10.4k
    e.Source = ImGuiInputSource_Mouse;
1751
10.4k
    e.EventId = g.InputEventsNextEventId++;
1752
10.4k
    e.MouseButton.Button = mouse_button;
1753
10.4k
    e.MouseButton.Down = down;
1754
10.4k
    e.MouseButton.MouseSource = g.InputEventsNextMouseSource;
1755
10.4k
    g.InputEventsQueue.push_back(e);
1756
10.4k
}
1757
1758
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1759
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1760
2.05k
{
1761
2.05k
    IM_ASSERT(Ctx != NULL);
1762
2.05k
    ImGuiContext& g = *Ctx;
1763
1764
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1765
2.05k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1766
31
        return;
1767
1768
2.02k
    ImGuiInputEvent e;
1769
2.02k
    e.Type = ImGuiInputEventType_MouseWheel;
1770
2.02k
    e.Source = ImGuiInputSource_Mouse;
1771
2.02k
    e.EventId = g.InputEventsNextEventId++;
1772
2.02k
    e.MouseWheel.WheelX = wheel_x;
1773
2.02k
    e.MouseWheel.WheelY = wheel_y;
1774
2.02k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1775
2.02k
    g.InputEventsQueue.push_back(e);
1776
2.02k
}
1777
1778
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1779
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1780
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1781
0
{
1782
0
    IM_ASSERT(Ctx != NULL);
1783
0
    ImGuiContext& g = *Ctx;
1784
0
    g.InputEventsNextMouseSource = source;
1785
0
}
1786
1787
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1788
0
{
1789
0
    IM_ASSERT(Ctx != NULL);
1790
0
    ImGuiContext& g = *Ctx;
1791
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1792
0
    if (!AppAcceptingEvents)
1793
0
        return;
1794
1795
    // Filter duplicate
1796
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1797
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1798
0
    if (latest_viewport_id == viewport_id)
1799
0
        return;
1800
1801
0
    ImGuiInputEvent e;
1802
0
    e.Type = ImGuiInputEventType_MouseViewport;
1803
0
    e.Source = ImGuiInputSource_Mouse;
1804
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1805
0
    g.InputEventsQueue.push_back(e);
1806
0
}
1807
1808
void ImGuiIO::AddFocusEvent(bool focused)
1809
2.44k
{
1810
2.44k
    IM_ASSERT(Ctx != NULL);
1811
2.44k
    ImGuiContext& g = *Ctx;
1812
1813
    // Filter duplicate
1814
2.44k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1815
2.44k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1816
2.44k
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1817
280
        return;
1818
1819
2.16k
    ImGuiInputEvent e;
1820
2.16k
    e.Type = ImGuiInputEventType_Focus;
1821
2.16k
    e.EventId = g.InputEventsNextEventId++;
1822
2.16k
    e.AppFocused.Focused = focused;
1823
2.16k
    g.InputEventsQueue.push_back(e);
1824
2.16k
}
1825
1826
//-----------------------------------------------------------------------------
1827
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1828
//-----------------------------------------------------------------------------
1829
1830
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1831
0
{
1832
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1833
0
    ImVec2 p_last = p1;
1834
0
    ImVec2 p_closest;
1835
0
    float p_closest_dist2 = FLT_MAX;
1836
0
    float t_step = 1.0f / (float)num_segments;
1837
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1838
0
    {
1839
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1840
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1841
0
        float dist2 = ImLengthSqr(p - p_line);
1842
0
        if (dist2 < p_closest_dist2)
1843
0
        {
1844
0
            p_closest = p_line;
1845
0
            p_closest_dist2 = dist2;
1846
0
        }
1847
0
        p_last = p_current;
1848
0
    }
1849
0
    return p_closest;
1850
0
}
1851
1852
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1853
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1854
0
{
1855
0
    float dx = x4 - x1;
1856
0
    float dy = y4 - y1;
1857
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1858
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1859
0
    d2 = (d2 >= 0) ? d2 : -d2;
1860
0
    d3 = (d3 >= 0) ? d3 : -d3;
1861
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1862
0
    {
1863
0
        ImVec2 p_current(x4, y4);
1864
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1865
0
        float dist2 = ImLengthSqr(p - p_line);
1866
0
        if (dist2 < p_closest_dist2)
1867
0
        {
1868
0
            p_closest = p_line;
1869
0
            p_closest_dist2 = dist2;
1870
0
        }
1871
0
        p_last = p_current;
1872
0
    }
1873
0
    else if (level < 10)
1874
0
    {
1875
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1876
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1877
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1878
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1879
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1880
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1881
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1882
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1883
0
    }
1884
0
}
1885
1886
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1887
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1888
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1889
0
{
1890
0
    IM_ASSERT(tess_tol > 0.0f);
1891
0
    ImVec2 p_last = p1;
1892
0
    ImVec2 p_closest;
1893
0
    float p_closest_dist2 = FLT_MAX;
1894
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1895
0
    return p_closest;
1896
0
}
1897
1898
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1899
0
{
1900
0
    ImVec2 ap = p - a;
1901
0
    ImVec2 ab_dir = b - a;
1902
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1903
0
    if (dot < 0.0f)
1904
0
        return a;
1905
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1906
0
    if (dot > ab_len_sqr)
1907
0
        return b;
1908
0
    return a + ab_dir * dot / ab_len_sqr;
1909
0
}
1910
1911
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1912
0
{
1913
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1914
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1915
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1916
0
    return ((b1 == b2) && (b2 == b3));
1917
0
}
1918
1919
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1920
0
{
1921
0
    ImVec2 v0 = b - a;
1922
0
    ImVec2 v1 = c - a;
1923
0
    ImVec2 v2 = p - a;
1924
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1925
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1926
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1927
0
    out_u = 1.0f - out_v - out_w;
1928
0
}
1929
1930
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1931
0
{
1932
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1933
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1934
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1935
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1936
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1937
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1938
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1939
0
    if (m == dist2_ab)
1940
0
        return proj_ab;
1941
0
    if (m == dist2_bc)
1942
0
        return proj_bc;
1943
0
    return proj_ca;
1944
0
}
1945
1946
//-----------------------------------------------------------------------------
1947
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1948
//-----------------------------------------------------------------------------
1949
1950
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1951
int ImStricmp(const char* str1, const char* str2)
1952
0
{
1953
0
    int d;
1954
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1955
0
    return d;
1956
0
}
1957
1958
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1959
0
{
1960
0
    int d = 0;
1961
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1962
0
    return d;
1963
0
}
1964
1965
void ImStrncpy(char* dst, const char* src, size_t count)
1966
3.48k
{
1967
3.48k
    if (count < 1)
1968
0
        return;
1969
3.48k
    if (count > 1)
1970
3.48k
        strncpy(dst, src, count - 1);
1971
3.48k
    dst[count - 1] = 0;
1972
3.48k
}
1973
1974
char* ImStrdup(const char* str)
1975
4
{
1976
4
    size_t len = strlen(str);
1977
4
    void* buf = IM_ALLOC(len + 1);
1978
4
    return (char*)memcpy(buf, (const void*)str, len + 1);
1979
4
}
1980
1981
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1982
0
{
1983
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1984
0
    size_t src_size = strlen(src) + 1;
1985
0
    if (dst_buf_size < src_size)
1986
0
    {
1987
0
        IM_FREE(dst);
1988
0
        dst = (char*)IM_ALLOC(src_size);
1989
0
        if (p_dst_size)
1990
0
            *p_dst_size = src_size;
1991
0
    }
1992
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1993
0
}
1994
1995
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1996
0
{
1997
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1998
0
    return p;
1999
0
}
2000
2001
int ImStrlenW(const ImWchar* str)
2002
0
{
2003
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
2004
0
    int n = 0;
2005
0
    while (*str++) n++;
2006
0
    return n;
2007
0
}
2008
2009
// Find end-of-line. Return pointer will point to either first \n, either str_end.
2010
const char* ImStreolRange(const char* str, const char* str_end)
2011
0
{
2012
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
2013
0
    return p ? p : str_end;
2014
0
}
2015
2016
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
2017
0
{
2018
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
2019
0
        buf_mid_line--;
2020
0
    return buf_mid_line;
2021
0
}
2022
2023
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
2024
0
{
2025
0
    if (!needle_end)
2026
0
        needle_end = needle + strlen(needle);
2027
2028
0
    const char un0 = (char)ImToUpper(*needle);
2029
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
2030
0
    {
2031
0
        if (ImToUpper(*haystack) == un0)
2032
0
        {
2033
0
            const char* b = needle + 1;
2034
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
2035
0
                if (ImToUpper(*a) != ImToUpper(*b))
2036
0
                    break;
2037
0
            if (b == needle_end)
2038
0
                return haystack;
2039
0
        }
2040
0
        haystack++;
2041
0
    }
2042
0
    return NULL;
2043
0
}
2044
2045
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
2046
void ImStrTrimBlanks(char* buf)
2047
0
{
2048
0
    char* p = buf;
2049
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
2050
0
        p++;
2051
0
    char* p_start = p;
2052
0
    while (*p != 0)                         // Find end of string
2053
0
        p++;
2054
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
2055
0
        p--;
2056
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
2057
0
        memmove(buf, p_start, p - p_start);
2058
0
    buf[p - p_start] = 0;                   // Zero terminate
2059
0
}
2060
2061
const char* ImStrSkipBlank(const char* str)
2062
0
{
2063
0
    while (str[0] == ' ' || str[0] == '\t')
2064
0
        str++;
2065
0
    return str;
2066
0
}
2067
2068
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
2069
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
2070
// B) When buf==NULL vsnprintf() will return the output size.
2071
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2072
2073
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
2074
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2075
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
2076
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
2077
#ifdef IMGUI_USE_STB_SPRINTF
2078
#ifndef IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION
2079
#define STB_SPRINTF_IMPLEMENTATION
2080
#endif
2081
#ifdef IMGUI_STB_SPRINTF_FILENAME
2082
#include IMGUI_STB_SPRINTF_FILENAME
2083
#else
2084
#include "stb_sprintf.h"
2085
#endif
2086
#endif // #ifdef IMGUI_USE_STB_SPRINTF
2087
2088
#if defined(_MSC_VER) && !defined(vsnprintf)
2089
#define vsnprintf _vsnprintf
2090
#endif
2091
2092
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
2093
4
{
2094
4
    va_list args;
2095
4
    va_start(args, fmt);
2096
#ifdef IMGUI_USE_STB_SPRINTF
2097
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2098
#else
2099
4
    int w = vsnprintf(buf, buf_size, fmt, args);
2100
4
#endif
2101
4
    va_end(args);
2102
4
    if (buf == NULL)
2103
0
        return w;
2104
4
    if (w == -1 || w >= (int)buf_size)
2105
0
        w = (int)buf_size - 1;
2106
4
    buf[w] = 0;
2107
4
    return w;
2108
4
}
2109
2110
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
2111
25.3k
{
2112
#ifdef IMGUI_USE_STB_SPRINTF
2113
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
2114
#else
2115
25.3k
    int w = vsnprintf(buf, buf_size, fmt, args);
2116
25.3k
#endif
2117
25.3k
    if (buf == NULL)
2118
0
        return w;
2119
25.3k
    if (w == -1 || w >= (int)buf_size)
2120
0
        w = (int)buf_size - 1;
2121
25.3k
    buf[w] = 0;
2122
25.3k
    return w;
2123
25.3k
}
2124
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
2125
2126
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
2127
25.3k
{
2128
25.3k
    va_list args;
2129
25.3k
    va_start(args, fmt);
2130
25.3k
    ImFormatStringToTempBufferV(out_buf, out_buf_end, fmt, args);
2131
25.3k
    va_end(args);
2132
25.3k
}
2133
2134
// FIXME: Should rework API toward allowing multiple in-flight temp buffers (easier and safer for caller)
2135
// by making the caller acquire a temp buffer token, with either explicit or destructor release, e.g.
2136
//  ImGuiTempBufferToken token;
2137
//  ImFormatStringToTempBuffer(token, ...);
2138
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
2139
25.3k
{
2140
25.3k
    ImGuiContext& g = *GImGui;
2141
25.3k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
2142
3
    {
2143
3
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
2144
3
        if (buf == NULL)
2145
0
            buf = "(null)";
2146
3
        *out_buf = buf;
2147
3
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
2148
3
    }
2149
25.3k
    else if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '*' && fmt[3] == 's' && fmt[4] == 0)
2150
0
    {
2151
0
        int buf_len = va_arg(args, int); // Skip formatting when using "%.*s"
2152
0
        const char* buf = va_arg(args, const char*);
2153
0
        if (buf == NULL)
2154
0
        {
2155
0
            buf = "(null)";
2156
0
            buf_len = ImMin(buf_len, 6);
2157
0
        }
2158
0
        *out_buf = buf;
2159
0
        *out_buf_end = buf + buf_len; // Disallow not passing 'out_buf_end' here. User is expected to use it.
2160
0
    }
2161
25.3k
    else
2162
25.3k
    {
2163
25.3k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
2164
25.3k
        *out_buf = g.TempBuffer.Data;
2165
25.3k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
2166
25.3k
    }
2167
25.3k
}
2168
2169
// CRC32 needs a 1KB lookup table (not cache friendly)
2170
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
2171
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
2172
static const ImU32 GCrc32LookupTable[256] =
2173
{
2174
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
2175
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
2176
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
2177
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
2178
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
2179
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
2180
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
2181
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
2182
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
2183
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
2184
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
2185
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
2186
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
2187
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
2188
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
2189
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
2190
};
2191
2192
// Known size hash
2193
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
2194
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2195
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
2196
152k
{
2197
152k
    ImU32 crc = ~seed;
2198
152k
    const unsigned char* data = (const unsigned char*)data_p;
2199
152k
    const ImU32* crc32_lut = GCrc32LookupTable;
2200
760k
    while (data_size-- != 0)
2201
608k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
2202
152k
    return ~crc;
2203
152k
}
2204
2205
// Zero-terminated string hash, with support for ### to reset back to seed value
2206
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2207
// Because this syntax is rarely used we are optimizing for the common case.
2208
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2209
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2210
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2211
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2212
550k
{
2213
550k
    seed = ~seed;
2214
550k
    ImU32 crc = seed;
2215
550k
    const unsigned char* data = (const unsigned char*)data_p;
2216
550k
    const ImU32* crc32_lut = GCrc32LookupTable;
2217
550k
    if (data_size != 0)
2218
0
    {
2219
0
        while (data_size-- != 0)
2220
0
        {
2221
0
            unsigned char c = *data++;
2222
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2223
0
                crc = seed;
2224
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2225
0
        }
2226
0
    }
2227
550k
    else
2228
550k
    {
2229
7.52M
        while (unsigned char c = *data++)
2230
6.97M
        {
2231
6.97M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2232
80.5k
                crc = seed;
2233
6.97M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2234
6.97M
        }
2235
550k
    }
2236
550k
    return ~crc;
2237
550k
}
2238
2239
//-----------------------------------------------------------------------------
2240
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2241
//-----------------------------------------------------------------------------
2242
2243
// Default file functions
2244
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2245
2246
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2247
0
{
2248
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2249
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2250
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2251
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2252
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2253
2254
    // Use stack buffer if possible, otherwise heap buffer. Sizes include zero terminator.
2255
    // We don't rely on current ImGuiContext as this is implied to be a helper function which doesn't depend on it (see #7314).
2256
    wchar_t local_temp_stack[FILENAME_MAX];
2257
    ImVector<wchar_t> local_temp_heap;
2258
    if (filename_wsize + mode_wsize > IM_ARRAYSIZE(local_temp_stack))
2259
        local_temp_heap.resize(filename_wsize + mode_wsize);
2260
    wchar_t* filename_wbuf = local_temp_heap.Data ? local_temp_heap.Data : local_temp_stack;
2261
    wchar_t* mode_wbuf = filename_wbuf + filename_wsize;
2262
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, filename_wbuf, filename_wsize);
2263
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, mode_wbuf, mode_wsize);
2264
    return ::_wfopen(filename_wbuf, mode_wbuf);
2265
#else
2266
0
    return fopen(filename, mode);
2267
0
#endif
2268
0
}
2269
2270
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2271
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2272
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2273
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2274
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2275
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2276
2277
// Helper: Load file content into memory
2278
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2279
// This can't really be used with "rt" because fseek size won't match read size.
2280
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2281
0
{
2282
0
    IM_ASSERT(filename && mode);
2283
0
    if (out_file_size)
2284
0
        *out_file_size = 0;
2285
2286
0
    ImFileHandle f;
2287
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2288
0
        return NULL;
2289
2290
0
    size_t file_size = (size_t)ImFileGetSize(f);
2291
0
    if (file_size == (size_t)-1)
2292
0
    {
2293
0
        ImFileClose(f);
2294
0
        return NULL;
2295
0
    }
2296
2297
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2298
0
    if (file_data == NULL)
2299
0
    {
2300
0
        ImFileClose(f);
2301
0
        return NULL;
2302
0
    }
2303
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2304
0
    {
2305
0
        ImFileClose(f);
2306
0
        IM_FREE(file_data);
2307
0
        return NULL;
2308
0
    }
2309
0
    if (padding_bytes > 0)
2310
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2311
2312
0
    ImFileClose(f);
2313
0
    if (out_file_size)
2314
0
        *out_file_size = file_size;
2315
2316
0
    return file_data;
2317
0
}
2318
2319
//-----------------------------------------------------------------------------
2320
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2321
//-----------------------------------------------------------------------------
2322
2323
IM_MSVC_RUNTIME_CHECKS_OFF
2324
2325
// Convert UTF-8 to 32-bit character, process single character input.
2326
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2327
// We handle UTF-8 decoding error by skipping forward.
2328
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2329
93.3k
{
2330
93.3k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2331
93.3k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2332
93.3k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2333
93.3k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2334
93.3k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2335
93.3k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2336
93.3k
    int wanted = len + (len ? 0 : 1);
2337
2338
93.3k
    if (in_text_end == NULL)
2339
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2340
2341
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2342
    // so it is fast even with excessive branching.
2343
93.3k
    unsigned char s[4];
2344
93.3k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2345
93.3k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2346
93.3k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2347
93.3k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2348
2349
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2350
93.3k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2351
93.3k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2352
93.3k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2353
93.3k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2354
93.3k
    *out_char >>= shiftc[len];
2355
2356
    // Accumulate the various error conditions.
2357
93.3k
    int e = 0;
2358
93.3k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2359
93.3k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2360
93.3k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2361
93.3k
    e |= (s[1] & 0xc0) >> 2;
2362
93.3k
    e |= (s[2] & 0xc0) >> 4;
2363
93.3k
    e |= (s[3]       ) >> 6;
2364
93.3k
    e ^= 0x2a; // top two bits of each tail byte correct?
2365
93.3k
    e >>= shifte[len];
2366
2367
93.3k
    if (e)
2368
20.9k
    {
2369
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2370
        // One byte is consumed in case of invalid first byte of in_text.
2371
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2372
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2373
20.9k
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2374
20.9k
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2375
20.9k
    }
2376
2377
93.3k
    return wanted;
2378
93.3k
}
2379
2380
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2381
0
{
2382
0
    ImWchar* buf_out = buf;
2383
0
    ImWchar* buf_end = buf + buf_size;
2384
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2385
0
    {
2386
0
        unsigned int c;
2387
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2388
0
        *buf_out++ = (ImWchar)c;
2389
0
    }
2390
0
    *buf_out = 0;
2391
0
    if (in_text_remaining)
2392
0
        *in_text_remaining = in_text;
2393
0
    return (int)(buf_out - buf);
2394
0
}
2395
2396
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2397
0
{
2398
0
    int char_count = 0;
2399
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2400
0
    {
2401
0
        unsigned int c;
2402
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2403
0
        char_count++;
2404
0
    }
2405
0
    return char_count;
2406
0
}
2407
2408
// Based on stb_to_utf8() from github.com/nothings/stb/
2409
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2410
0
{
2411
0
    if (c < 0x80)
2412
0
    {
2413
0
        buf[0] = (char)c;
2414
0
        return 1;
2415
0
    }
2416
0
    if (c < 0x800)
2417
0
    {
2418
0
        if (buf_size < 2) return 0;
2419
0
        buf[0] = (char)(0xc0 + (c >> 6));
2420
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2421
0
        return 2;
2422
0
    }
2423
0
    if (c < 0x10000)
2424
0
    {
2425
0
        if (buf_size < 3) return 0;
2426
0
        buf[0] = (char)(0xe0 + (c >> 12));
2427
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2428
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2429
0
        return 3;
2430
0
    }
2431
0
    if (c <= 0x10FFFF)
2432
0
    {
2433
0
        if (buf_size < 4) return 0;
2434
0
        buf[0] = (char)(0xf0 + (c >> 18));
2435
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2436
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2437
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2438
0
        return 4;
2439
0
    }
2440
    // Invalid code point, the max unicode is 0x10FFFF
2441
0
    return 0;
2442
0
}
2443
2444
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2445
0
{
2446
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2447
0
    out_buf[count] = 0;
2448
0
    return out_buf;
2449
0
}
2450
2451
// Not optimal but we very rarely use this function.
2452
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2453
0
{
2454
0
    unsigned int unused = 0;
2455
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2456
0
}
2457
2458
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2459
0
{
2460
0
    if (c < 0x80) return 1;
2461
0
    if (c < 0x800) return 2;
2462
0
    if (c < 0x10000) return 3;
2463
0
    if (c <= 0x10FFFF) return 4;
2464
0
    return 3;
2465
0
}
2466
2467
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2468
0
{
2469
0
    char* buf_p = out_buf;
2470
0
    const char* buf_end = out_buf + out_buf_size;
2471
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2472
0
    {
2473
0
        unsigned int c = (unsigned int)(*in_text++);
2474
0
        if (c < 0x80)
2475
0
            *buf_p++ = (char)c;
2476
0
        else
2477
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2478
0
    }
2479
0
    *buf_p = 0;
2480
0
    return (int)(buf_p - out_buf);
2481
0
}
2482
2483
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2484
0
{
2485
0
    int bytes_count = 0;
2486
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2487
0
    {
2488
0
        unsigned int c = (unsigned int)(*in_text++);
2489
0
        if (c < 0x80)
2490
0
            bytes_count++;
2491
0
        else
2492
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2493
0
    }
2494
0
    return bytes_count;
2495
0
}
2496
2497
const char* ImTextFindPreviousUtf8Codepoint(const char* in_text_start, const char* in_text_curr)
2498
0
{
2499
0
    while (in_text_curr > in_text_start)
2500
0
    {
2501
0
        in_text_curr--;
2502
0
        if ((*in_text_curr & 0xC0) != 0x80)
2503
0
            return in_text_curr;
2504
0
    }
2505
0
    return in_text_start;
2506
0
}
2507
2508
int ImTextCountLines(const char* in_text, const char* in_text_end)
2509
0
{
2510
0
    if (in_text_end == NULL)
2511
0
        in_text_end = in_text + strlen(in_text); // FIXME-OPT: Not optimal approach, discourage use for now.
2512
0
    int count = 0;
2513
0
    while (in_text < in_text_end)
2514
0
    {
2515
0
        const char* line_end = (const char*)memchr(in_text, '\n', in_text_end - in_text);
2516
0
        in_text = line_end ? line_end + 1 : in_text_end;
2517
0
        count++;
2518
0
    }
2519
0
    return count;
2520
0
}
2521
2522
IM_MSVC_RUNTIME_CHECKS_RESTORE
2523
2524
//-----------------------------------------------------------------------------
2525
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2526
// Note: The Convert functions are early design which are not consistent with other API.
2527
//-----------------------------------------------------------------------------
2528
2529
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2530
0
{
2531
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2532
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2533
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2534
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2535
0
    return IM_COL32(r, g, b, 0xFF);
2536
0
}
2537
2538
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2539
216k
{
2540
216k
    float s = 1.0f / 255.0f;
2541
216k
    return ImVec4(
2542
216k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2543
216k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2544
216k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2545
216k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2546
216k
}
2547
2548
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2549
1.24M
{
2550
1.24M
    ImU32 out;
2551
1.24M
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2552
1.24M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2553
1.24M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2554
1.24M
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2555
1.24M
    return out;
2556
1.24M
}
2557
2558
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2559
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2560
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2561
0
{
2562
0
    float K = 0.f;
2563
0
    if (g < b)
2564
0
    {
2565
0
        ImSwap(g, b);
2566
0
        K = -1.f;
2567
0
    }
2568
0
    if (r < g)
2569
0
    {
2570
0
        ImSwap(r, g);
2571
0
        K = -2.f / 6.f - K;
2572
0
    }
2573
2574
0
    const float chroma = r - (g < b ? g : b);
2575
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2576
0
    out_s = chroma / (r + 1e-20f);
2577
0
    out_v = r;
2578
0
}
2579
2580
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2581
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2582
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2583
0
{
2584
0
    if (s == 0.0f)
2585
0
    {
2586
        // gray
2587
0
        out_r = out_g = out_b = v;
2588
0
        return;
2589
0
    }
2590
2591
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2592
0
    int   i = (int)h;
2593
0
    float f = h - (float)i;
2594
0
    float p = v * (1.0f - s);
2595
0
    float q = v * (1.0f - s * f);
2596
0
    float t = v * (1.0f - s * (1.0f - f));
2597
2598
0
    switch (i)
2599
0
    {
2600
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2601
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2602
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2603
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2604
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2605
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2606
0
    }
2607
0
}
2608
2609
//-----------------------------------------------------------------------------
2610
// [SECTION] ImGuiStorage
2611
// Helper: Key->value storage
2612
//-----------------------------------------------------------------------------
2613
2614
// std::lower_bound but without the bullshit
2615
ImGuiStoragePair* ImLowerBound(ImGuiStoragePair* in_begin, ImGuiStoragePair* in_end, ImGuiID key)
2616
186k
{
2617
186k
    ImGuiStoragePair* in_p = in_begin;
2618
625k
    for (size_t count = (size_t)(in_end - in_p); count > 0; )
2619
439k
    {
2620
439k
        size_t count2 = count >> 1;
2621
439k
        ImGuiStoragePair* mid = in_p + count2;
2622
439k
        if (mid->key < key)
2623
105k
        {
2624
105k
            in_p = ++mid;
2625
105k
            count -= count2 + 1;
2626
105k
        }
2627
333k
        else
2628
333k
        {
2629
333k
            count = count2;
2630
333k
        }
2631
439k
    }
2632
186k
    return in_p;
2633
186k
}
2634
2635
IM_MSVC_RUNTIME_CHECKS_OFF
2636
static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2637
0
{
2638
    // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2639
0
    ImGuiID lhs_v = ((const ImGuiStoragePair*)lhs)->key;
2640
0
    ImGuiID rhs_v = ((const ImGuiStoragePair*)rhs)->key;
2641
0
    return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
2642
0
}
2643
2644
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2645
void ImGuiStorage::BuildSortByKey()
2646
0
{
2647
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), PairComparerByID);
2648
0
}
2649
2650
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2651
0
{
2652
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2653
0
    if (it == Data.Data + Data.Size || it->key != key)
2654
0
        return default_val;
2655
0
    return it->val_i;
2656
0
}
2657
2658
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2659
0
{
2660
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2661
0
}
2662
2663
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2664
0
{
2665
0
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2666
0
    if (it == Data.Data + Data.Size || it->key != key)
2667
0
        return default_val;
2668
0
    return it->val_f;
2669
0
}
2670
2671
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2672
186k
{
2673
186k
    ImGuiStoragePair* it = ImLowerBound(const_cast<ImGuiStoragePair*>(Data.Data), const_cast<ImGuiStoragePair*>(Data.Data + Data.Size), key);
2674
186k
    if (it == Data.Data + Data.Size || it->key != key)
2675
4
        return NULL;
2676
186k
    return it->val_p;
2677
186k
}
2678
2679
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2680
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2681
0
{
2682
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2683
0
    if (it == Data.Data + Data.Size || it->key != key)
2684
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2685
0
    return &it->val_i;
2686
0
}
2687
2688
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2689
0
{
2690
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2691
0
}
2692
2693
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2694
0
{
2695
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2696
0
    if (it == Data.Data + Data.Size || it->key != key)
2697
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2698
0
    return &it->val_f;
2699
0
}
2700
2701
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2702
0
{
2703
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2704
0
    if (it == Data.Data + Data.Size || it->key != key)
2705
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2706
0
    return &it->val_p;
2707
0
}
2708
2709
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2710
void ImGuiStorage::SetInt(ImGuiID key, int val)
2711
0
{
2712
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2713
0
    if (it == Data.Data + Data.Size || it->key != key)
2714
0
        Data.insert(it, ImGuiStoragePair(key, val));
2715
0
    else
2716
0
        it->val_i = val;
2717
0
}
2718
2719
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2720
0
{
2721
0
    SetInt(key, val ? 1 : 0);
2722
0
}
2723
2724
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2725
0
{
2726
0
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2727
0
    if (it == Data.Data + Data.Size || it->key != key)
2728
0
        Data.insert(it, ImGuiStoragePair(key, val));
2729
0
    else
2730
0
        it->val_f = val;
2731
0
}
2732
2733
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2734
4
{
2735
4
    ImGuiStoragePair* it = ImLowerBound(Data.Data, Data.Data + Data.Size, key);
2736
4
    if (it == Data.Data + Data.Size || it->key != key)
2737
4
        Data.insert(it, ImGuiStoragePair(key, val));
2738
0
    else
2739
0
        it->val_p = val;
2740
4
}
2741
2742
void ImGuiStorage::SetAllInt(int v)
2743
0
{
2744
0
    for (int i = 0; i < Data.Size; i++)
2745
0
        Data[i].val_i = v;
2746
0
}
2747
IM_MSVC_RUNTIME_CHECKS_RESTORE
2748
2749
//-----------------------------------------------------------------------------
2750
// [SECTION] ImGuiTextFilter
2751
//-----------------------------------------------------------------------------
2752
2753
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2754
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2755
0
{
2756
0
    InputBuf[0] = 0;
2757
0
    CountGrep = 0;
2758
0
    if (default_filter)
2759
0
    {
2760
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2761
0
        Build();
2762
0
    }
2763
0
}
2764
2765
bool ImGuiTextFilter::Draw(const char* label, float width)
2766
0
{
2767
0
    if (width != 0.0f)
2768
0
        ImGui::SetNextItemWidth(width);
2769
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2770
0
    if (value_changed)
2771
0
        Build();
2772
0
    return value_changed;
2773
0
}
2774
2775
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2776
0
{
2777
0
    out->resize(0);
2778
0
    const char* wb = b;
2779
0
    const char* we = wb;
2780
0
    while (we < e)
2781
0
    {
2782
0
        if (*we == separator)
2783
0
        {
2784
0
            out->push_back(ImGuiTextRange(wb, we));
2785
0
            wb = we + 1;
2786
0
        }
2787
0
        we++;
2788
0
    }
2789
0
    if (wb != we)
2790
0
        out->push_back(ImGuiTextRange(wb, we));
2791
0
}
2792
2793
void ImGuiTextFilter::Build()
2794
0
{
2795
0
    Filters.resize(0);
2796
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2797
0
    input_range.split(',', &Filters);
2798
2799
0
    CountGrep = 0;
2800
0
    for (ImGuiTextRange& f : Filters)
2801
0
    {
2802
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2803
0
            f.b++;
2804
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2805
0
            f.e--;
2806
0
        if (f.empty())
2807
0
            continue;
2808
0
        if (f.b[0] != '-')
2809
0
            CountGrep += 1;
2810
0
    }
2811
0
}
2812
2813
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2814
0
{
2815
0
    if (Filters.Size == 0)
2816
0
        return true;
2817
2818
0
    if (text == NULL)
2819
0
        text = text_end = "";
2820
2821
0
    for (const ImGuiTextRange& f : Filters)
2822
0
    {
2823
0
        if (f.b == f.e)
2824
0
            continue;
2825
0
        if (f.b[0] == '-')
2826
0
        {
2827
            // Subtract
2828
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2829
0
                return false;
2830
0
        }
2831
0
        else
2832
0
        {
2833
            // Grep
2834
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2835
0
                return true;
2836
0
        }
2837
0
    }
2838
2839
    // Implicit * grep
2840
0
    if (CountGrep == 0)
2841
0
        return true;
2842
2843
0
    return false;
2844
0
}
2845
2846
//-----------------------------------------------------------------------------
2847
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2848
//-----------------------------------------------------------------------------
2849
2850
// On some platform vsnprintf() takes va_list by reference and modifies it.
2851
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2852
#ifndef va_copy
2853
#if defined(__GNUC__) || defined(__clang__)
2854
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2855
#else
2856
#define va_copy(dest, src) (dest = src)
2857
#endif
2858
#endif
2859
2860
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2861
2862
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2863
0
{
2864
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2865
2866
    // Add zero-terminator the first time
2867
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2868
0
    const int needed_sz = write_off + len;
2869
0
    if (write_off + len >= Buf.Capacity)
2870
0
    {
2871
0
        int new_capacity = Buf.Capacity * 2;
2872
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2873
0
    }
2874
2875
0
    Buf.resize(needed_sz);
2876
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2877
0
    Buf[write_off - 1 + len] = 0;
2878
0
}
2879
2880
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2881
0
{
2882
0
    va_list args;
2883
0
    va_start(args, fmt);
2884
0
    appendfv(fmt, args);
2885
0
    va_end(args);
2886
0
}
2887
2888
// Helper: Text buffer for logging/accumulating text
2889
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2890
0
{
2891
0
    va_list args_copy;
2892
0
    va_copy(args_copy, args);
2893
2894
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2895
0
    if (len <= 0)
2896
0
    {
2897
0
        va_end(args_copy);
2898
0
        return;
2899
0
    }
2900
2901
    // Add zero-terminator the first time
2902
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2903
0
    const int needed_sz = write_off + len;
2904
0
    if (write_off + len >= Buf.Capacity)
2905
0
    {
2906
0
        int new_capacity = Buf.Capacity * 2;
2907
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2908
0
    }
2909
2910
0
    Buf.resize(needed_sz);
2911
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2912
0
    va_end(args_copy);
2913
0
}
2914
2915
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2916
0
{
2917
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2918
0
    if (old_size == new_size)
2919
0
        return;
2920
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2921
0
        LineOffsets.push_back(EndOffset);
2922
0
    const char* base_end = base + new_size;
2923
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2924
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2925
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2926
0
    EndOffset = ImMax(EndOffset, new_size);
2927
0
}
2928
2929
//-----------------------------------------------------------------------------
2930
// [SECTION] ImGuiListClipper
2931
//-----------------------------------------------------------------------------
2932
2933
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2934
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2935
static bool GetSkipItemForListClipping()
2936
0
{
2937
0
    ImGuiContext& g = *GImGui;
2938
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2939
0
}
2940
2941
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2942
0
{
2943
0
    if (ranges.Size - offset <= 1)
2944
0
        return;
2945
2946
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2947
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2948
0
        for (int i = offset; i < sort_end + offset; ++i)
2949
0
            if (ranges[i].Min > ranges[i + 1].Min)
2950
0
                ImSwap(ranges[i], ranges[i + 1]);
2951
2952
    // Now fuse ranges together as much as possible.
2953
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2954
0
    {
2955
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2956
0
        if (ranges[i - 1].Max < ranges[i].Min)
2957
0
            continue;
2958
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2959
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2960
0
        ranges.erase(ranges.Data + i);
2961
0
        i--;
2962
0
    }
2963
0
}
2964
2965
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2966
0
{
2967
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2968
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2969
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2970
0
    ImGuiContext& g = *GImGui;
2971
0
    ImGuiWindow* window = g.CurrentWindow;
2972
0
    float off_y = pos_y - window->DC.CursorPos.y;
2973
0
    window->DC.CursorPos.y = pos_y;
2974
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2975
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2976
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2977
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2978
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2979
0
    if (ImGuiTable* table = g.CurrentTable)
2980
0
    {
2981
0
        if (table->IsInsideRow)
2982
0
            ImGui::TableEndRow(table);
2983
0
        table->RowPosY2 = window->DC.CursorPos.y;
2984
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2985
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2986
0
        table->RowBgColorCounter += row_increase;
2987
0
    }
2988
0
}
2989
2990
ImGuiListClipper::ImGuiListClipper()
2991
0
{
2992
0
    memset(this, 0, sizeof(*this));
2993
0
}
2994
2995
ImGuiListClipper::~ImGuiListClipper()
2996
0
{
2997
0
    End();
2998
0
}
2999
3000
void ImGuiListClipper::Begin(int items_count, float items_height)
3001
0
{
3002
0
    if (Ctx == NULL)
3003
0
        Ctx = ImGui::GetCurrentContext();
3004
3005
0
    ImGuiContext& g = *Ctx;
3006
0
    ImGuiWindow* window = g.CurrentWindow;
3007
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
3008
3009
0
    if (ImGuiTable* table = g.CurrentTable)
3010
0
        if (table->IsInsideRow)
3011
0
            ImGui::TableEndRow(table);
3012
3013
0
    StartPosY = window->DC.CursorPos.y;
3014
0
    ItemsHeight = items_height;
3015
0
    ItemsCount = items_count;
3016
0
    DisplayStart = -1;
3017
0
    DisplayEnd = 0;
3018
3019
    // Acquire temporary buffer
3020
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
3021
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
3022
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3023
0
    data->Reset(this);
3024
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
3025
0
    TempData = data;
3026
0
    StartSeekOffsetY = data->LossynessOffset;
3027
0
}
3028
3029
void ImGuiListClipper::End()
3030
0
{
3031
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
3032
0
    {
3033
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
3034
0
        ImGuiContext& g = *Ctx;
3035
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
3036
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
3037
0
            SeekCursorForItem(ItemsCount);
3038
3039
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
3040
0
        IM_ASSERT(data->ListClipper == this);
3041
0
        data->StepNo = data->Ranges.Size;
3042
0
        if (--g.ClipperTempDataStacked > 0)
3043
0
        {
3044
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
3045
0
            data->ListClipper->TempData = data;
3046
0
        }
3047
0
        TempData = NULL;
3048
0
    }
3049
0
    ItemsCount = -1;
3050
0
}
3051
3052
void ImGuiListClipper::IncludeItemsByIndex(int item_begin, int item_end)
3053
0
{
3054
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
3055
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
3056
0
    IM_ASSERT(item_begin <= item_end);
3057
0
    if (item_begin < item_end)
3058
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
3059
0
}
3060
3061
// This is already called while stepping.
3062
// The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper::Begin() because you couldn't step item count beforehand.
3063
void ImGuiListClipper::SeekCursorForItem(int item_n)
3064
0
{
3065
    // - Perform the add and multiply with double to allow seeking through larger ranges.
3066
    // - StartPosY starts from ItemsFrozen, by adding SeekOffsetY we generally cancel that out (SeekOffsetY == LossynessOffset - ItemsFrozen * ItemsHeight).
3067
    // - The reason we store SeekOffsetY instead of inferring it, is because we want to allow user to perform Seek after the last step, where ImGuiListClipperData is already done.
3068
0
    float pos_y = (float)((double)StartPosY + StartSeekOffsetY + (double)item_n * ItemsHeight);
3069
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, ItemsHeight);
3070
0
}
3071
3072
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
3073
0
{
3074
0
    ImGuiContext& g = *clipper->Ctx;
3075
0
    ImGuiWindow* window = g.CurrentWindow;
3076
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
3077
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
3078
3079
0
    ImGuiTable* table = g.CurrentTable;
3080
0
    if (table && table->IsInsideRow)
3081
0
        ImGui::TableEndRow(table);
3082
3083
    // No items
3084
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
3085
0
        return false;
3086
3087
    // While we are in frozen row state, keep displaying items one by one, unclipped
3088
    // FIXME: Could be stored as a table-agnostic state.
3089
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
3090
0
    {
3091
0
        clipper->DisplayStart = data->ItemsFrozen;
3092
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
3093
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
3094
0
            data->ItemsFrozen++;
3095
0
        return true;
3096
0
    }
3097
3098
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
3099
0
    bool calc_clipping = false;
3100
0
    if (data->StepNo == 0)
3101
0
    {
3102
0
        clipper->StartPosY = window->DC.CursorPos.y;
3103
0
        if (clipper->ItemsHeight <= 0.0f)
3104
0
        {
3105
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
3106
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
3107
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
3108
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
3109
0
            data->StepNo = 1;
3110
0
            return true;
3111
0
        }
3112
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
3113
0
    }
3114
3115
    // Step 1: Let the clipper infer height from first range
3116
0
    if (clipper->ItemsHeight <= 0.0f)
3117
0
    {
3118
0
        IM_ASSERT(data->StepNo == 1);
3119
0
        if (table)
3120
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
3121
3122
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
3123
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
3124
0
        if (affected_by_floating_point_precision)
3125
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
3126
3127
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
3128
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
3129
0
    }
3130
3131
    // Step 0 or 1: Calculate the actual ranges of visible elements.
3132
0
    const int already_submitted = clipper->DisplayEnd;
3133
0
    if (calc_clipping)
3134
0
    {
3135
        // Record seek offset, this is so ImGuiListClipper::Seek() can be called after ImGuiListClipperData is done
3136
0
        clipper->StartSeekOffsetY = (double)data->LossynessOffset - data->ItemsFrozen * (double)clipper->ItemsHeight;
3137
3138
0
        if (g.LogEnabled)
3139
0
        {
3140
            // If logging is active, do not perform any clipping
3141
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
3142
0
        }
3143
0
        else
3144
0
        {
3145
            // Add range selected to be included for navigation
3146
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
3147
0
            if (is_nav_request)
3148
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
3149
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && g.NavTabbingDir == -1)
3150
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
3151
3152
            // Add focused/active item
3153
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
3154
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
3155
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
3156
3157
            // Add visible range
3158
0
            float min_y = window->ClipRect.Min.y;
3159
0
            float max_y = window->ClipRect.Max.y;
3160
3161
            // Add box selection range
3162
0
            ImGuiBoxSelectState* bs = &g.BoxSelectState;
3163
0
            if (bs->IsActive && bs->Window == window)
3164
0
            {
3165
                // FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos.
3166
                // RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that.
3167
                // As a workaround we currently half ItemSpacing worth on each side.
3168
0
                min_y -= g.Style.ItemSpacing.y;
3169
0
                max_y += g.Style.ItemSpacing.y;
3170
3171
                // Box-select on 2D area requires different clipping.
3172
0
                if (bs->UnclipMode)
3173
0
                    data->Ranges.push_back(ImGuiListClipperRange::FromPositions(bs->UnclipRect.Min.y, bs->UnclipRect.Max.y, 0, 0));
3174
0
            }
3175
3176
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
3177
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
3178
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(min_y, max_y, off_min, off_max));
3179
0
        }
3180
3181
        // Convert position ranges to item index ranges
3182
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
3183
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
3184
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
3185
0
        for (ImGuiListClipperRange& range : data->Ranges)
3186
0
            if (range.PosToIndexConvert)
3187
0
            {
3188
0
                int m1 = (int)(((double)range.Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
3189
0
                int m2 = (int)((((double)range.Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
3190
0
                range.Min = ImClamp(already_submitted + m1 + range.PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
3191
0
                range.Max = ImClamp(already_submitted + m2 + range.PosToIndexOffsetMax, range.Min + 1, clipper->ItemsCount);
3192
0
                range.PosToIndexConvert = false;
3193
0
            }
3194
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
3195
0
    }
3196
3197
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
3198
0
    while (data->StepNo < data->Ranges.Size)
3199
0
    {
3200
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3201
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3202
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3203
0
            clipper->SeekCursorForItem(clipper->DisplayStart);
3204
0
        data->StepNo++;
3205
0
        if (clipper->DisplayStart == clipper->DisplayEnd && data->StepNo < data->Ranges.Size)
3206
0
            continue;
3207
0
        return true;
3208
0
    }
3209
3210
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3211
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3212
0
    if (clipper->ItemsCount < INT_MAX)
3213
0
        clipper->SeekCursorForItem(clipper->ItemsCount);
3214
3215
0
    return false;
3216
0
}
3217
3218
bool ImGuiListClipper::Step()
3219
0
{
3220
0
    ImGuiContext& g = *Ctx;
3221
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3222
0
    bool ret = ImGuiListClipper_StepInternal(this);
3223
0
    if (ret && (DisplayStart == DisplayEnd))
3224
0
        ret = false;
3225
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3226
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3227
0
    if (need_items_height && ItemsHeight > 0.0f)
3228
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3229
0
    if (ret)
3230
0
    {
3231
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3232
0
    }
3233
0
    else
3234
0
    {
3235
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3236
0
        End();
3237
0
    }
3238
0
    return ret;
3239
0
}
3240
3241
//-----------------------------------------------------------------------------
3242
// [SECTION] STYLING
3243
//-----------------------------------------------------------------------------
3244
3245
ImGuiStyle& ImGui::GetStyle()
3246
135k
{
3247
135k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3248
135k
    return GImGui->Style;
3249
135k
}
3250
3251
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3252
1.08M
{
3253
1.08M
    ImGuiStyle& style = GImGui->Style;
3254
1.08M
    ImVec4 c = style.Colors[idx];
3255
1.08M
    c.w *= style.Alpha * alpha_mul;
3256
1.08M
    return ColorConvertFloat4ToU32(c);
3257
1.08M
}
3258
3259
ImU32 ImGui::GetColorU32(const ImVec4& col)
3260
0
{
3261
0
    ImGuiStyle& style = GImGui->Style;
3262
0
    ImVec4 c = col;
3263
0
    c.w *= style.Alpha;
3264
0
    return ColorConvertFloat4ToU32(c);
3265
0
}
3266
3267
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3268
0
{
3269
0
    ImGuiStyle& style = GImGui->Style;
3270
0
    return style.Colors[idx];
3271
0
}
3272
3273
ImU32 ImGui::GetColorU32(ImU32 col, float alpha_mul)
3274
0
{
3275
0
    ImGuiStyle& style = GImGui->Style;
3276
0
    alpha_mul *= style.Alpha;
3277
0
    if (alpha_mul >= 1.0f)
3278
0
        return col;
3279
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3280
0
    a = (ImU32)(a * alpha_mul); // We don't need to clamp 0..255 because alpha is in 0..1 range.
3281
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3282
0
}
3283
3284
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3285
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3286
0
{
3287
0
    ImGuiContext& g = *GImGui;
3288
0
    ImGuiColorMod backup;
3289
0
    backup.Col = idx;
3290
0
    backup.BackupValue = g.Style.Colors[idx];
3291
0
    g.ColorStack.push_back(backup);
3292
0
    if (g.DebugFlashStyleColorIdx != idx)
3293
0
        g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3294
0
}
3295
3296
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3297
80.5k
{
3298
80.5k
    ImGuiContext& g = *GImGui;
3299
80.5k
    ImGuiColorMod backup;
3300
80.5k
    backup.Col = idx;
3301
80.5k
    backup.BackupValue = g.Style.Colors[idx];
3302
80.5k
    g.ColorStack.push_back(backup);
3303
80.5k
    if (g.DebugFlashStyleColorIdx != idx)
3304
80.5k
        g.Style.Colors[idx] = col;
3305
80.5k
}
3306
3307
void ImGui::PopStyleColor(int count)
3308
80.5k
{
3309
80.5k
    ImGuiContext& g = *GImGui;
3310
80.5k
    if (g.ColorStack.Size < count)
3311
0
    {
3312
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times!");
3313
0
        count = g.ColorStack.Size;
3314
0
    }
3315
161k
    while (count > 0)
3316
80.5k
    {
3317
80.5k
        ImGuiColorMod& backup = g.ColorStack.back();
3318
80.5k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3319
80.5k
        g.ColorStack.pop_back();
3320
80.5k
        count--;
3321
80.5k
    }
3322
80.5k
}
3323
3324
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3325
{
3326
    ImGuiCol_Text, ImGuiCol_TabHovered, ImGuiCol_Tab, ImGuiCol_TabSelected, ImGuiCol_TabSelectedOverline, ImGuiCol_TabDimmed, ImGuiCol_TabDimmedSelected, ImGuiCol_TabDimmedSelectedOverline,
3327
};
3328
3329
static const ImGuiDataVarInfo GStyleVarInfo[] =
3330
{
3331
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, Alpha) },                     // ImGuiStyleVar_Alpha
3332
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DisabledAlpha) },             // ImGuiStyleVar_DisabledAlpha
3333
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowPadding) },             // ImGuiStyleVar_WindowPadding
3334
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowRounding) },            // ImGuiStyleVar_WindowRounding
3335
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, WindowBorderSize) },          // ImGuiStyleVar_WindowBorderSize
3336
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowMinSize) },             // ImGuiStyleVar_WindowMinSize
3337
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, WindowTitleAlign) },          // ImGuiStyleVar_WindowTitleAlign
3338
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildRounding) },             // ImGuiStyleVar_ChildRounding
3339
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ChildBorderSize) },           // ImGuiStyleVar_ChildBorderSize
3340
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupRounding) },             // ImGuiStyleVar_PopupRounding
3341
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, PopupBorderSize) },           // ImGuiStyleVar_PopupBorderSize
3342
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, FramePadding) },              // ImGuiStyleVar_FramePadding
3343
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameRounding) },             // ImGuiStyleVar_FrameRounding
3344
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, FrameBorderSize) },           // ImGuiStyleVar_FrameBorderSize
3345
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemSpacing) },               // ImGuiStyleVar_ItemSpacing
3346
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ItemInnerSpacing) },          // ImGuiStyleVar_ItemInnerSpacing
3347
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, IndentSpacing) },             // ImGuiStyleVar_IndentSpacing
3348
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, CellPadding) },               // ImGuiStyleVar_CellPadding
3349
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarSize) },             // ImGuiStyleVar_ScrollbarSize
3350
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, ScrollbarRounding) },         // ImGuiStyleVar_ScrollbarRounding
3351
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabMinSize) },               // ImGuiStyleVar_GrabMinSize
3352
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, GrabRounding) },              // ImGuiStyleVar_GrabRounding
3353
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabRounding) },               // ImGuiStyleVar_TabRounding
3354
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBorderSize) },             // ImGuiStyleVar_TabBorderSize
3355
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarBorderSize) },          // ImGuiStyleVar_TabBarBorderSize
3356
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TabBarOverlineSize) },        // ImGuiStyleVar_TabBarOverlineSize
3357
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersAngle)},    // ImGuiStyleVar_TableAngledHeadersAngle
3358
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, TableAngledHeadersTextAlign)},// ImGuiStyleVar_TableAngledHeadersTextAlign
3359
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, ButtonTextAlign) },           // ImGuiStyleVar_ButtonTextAlign
3360
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SelectableTextAlign) },       // ImGuiStyleVar_SelectableTextAlign
3361
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, SeparatorTextBorderSize)},    // ImGuiStyleVar_SeparatorTextBorderSize
3362
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextAlign) },        // ImGuiStyleVar_SeparatorTextAlign
3363
    { ImGuiDataType_Float, 2, (ImU32)offsetof(ImGuiStyle, SeparatorTextPadding) },      // ImGuiStyleVar_SeparatorTextPadding
3364
    { ImGuiDataType_Float, 1, (ImU32)offsetof(ImGuiStyle, DockingSeparatorSize) },      // ImGuiStyleVar_DockingSeparatorSize
3365
};
3366
3367
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3368
161k
{
3369
161k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3370
161k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3371
161k
    return &GStyleVarInfo[idx];
3372
161k
}
3373
3374
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3375
0
{
3376
0
    ImGuiContext& g = *GImGui;
3377
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3378
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3379
0
    {
3380
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3381
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3382
0
        *pvar = val;
3383
0
        return;
3384
0
    }
3385
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3386
0
}
3387
3388
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3389
80.5k
{
3390
80.5k
    ImGuiContext& g = *GImGui;
3391
80.5k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3392
80.5k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3393
80.5k
    {
3394
80.5k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3395
80.5k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3396
80.5k
        *pvar = val;
3397
80.5k
        return;
3398
80.5k
    }
3399
0
    IM_ASSERT_USER_ERROR(0, "Calling PushStyleVar() variant with wrong type!");
3400
0
}
3401
3402
void ImGui::PopStyleVar(int count)
3403
80.5k
{
3404
80.5k
    ImGuiContext& g = *GImGui;
3405
80.5k
    if (g.StyleVarStack.Size < count)
3406
0
    {
3407
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times!");
3408
0
        count = g.StyleVarStack.Size;
3409
0
    }
3410
161k
    while (count > 0)
3411
80.5k
    {
3412
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3413
80.5k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3414
80.5k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3415
80.5k
        void* data = info->GetVarPtr(&g.Style);
3416
80.5k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3417
80.5k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3418
80.5k
        g.StyleVarStack.pop_back();
3419
80.5k
        count--;
3420
80.5k
    }
3421
80.5k
}
3422
3423
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3424
0
{
3425
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3426
0
    switch (idx)
3427
0
    {
3428
0
    case ImGuiCol_Text: return "Text";
3429
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3430
0
    case ImGuiCol_WindowBg: return "WindowBg";
3431
0
    case ImGuiCol_ChildBg: return "ChildBg";
3432
0
    case ImGuiCol_PopupBg: return "PopupBg";
3433
0
    case ImGuiCol_Border: return "Border";
3434
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3435
0
    case ImGuiCol_FrameBg: return "FrameBg";
3436
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3437
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3438
0
    case ImGuiCol_TitleBg: return "TitleBg";
3439
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3440
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3441
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3442
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3443
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3444
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3445
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3446
0
    case ImGuiCol_CheckMark: return "CheckMark";
3447
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3448
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3449
0
    case ImGuiCol_Button: return "Button";
3450
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3451
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3452
0
    case ImGuiCol_Header: return "Header";
3453
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3454
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3455
0
    case ImGuiCol_Separator: return "Separator";
3456
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3457
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3458
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3459
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3460
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3461
0
    case ImGuiCol_TabHovered: return "TabHovered";
3462
0
    case ImGuiCol_Tab: return "Tab";
3463
0
    case ImGuiCol_TabSelected: return "TabSelected";
3464
0
    case ImGuiCol_TabSelectedOverline: return "TabSelectedOverline";
3465
0
    case ImGuiCol_TabDimmed: return "TabDimmed";
3466
0
    case ImGuiCol_TabDimmedSelected: return "TabDimmedSelected";
3467
0
    case ImGuiCol_TabDimmedSelectedOverline: return "TabDimmedSelectedOverline";
3468
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3469
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3470
0
    case ImGuiCol_PlotLines: return "PlotLines";
3471
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3472
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3473
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3474
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3475
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3476
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3477
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3478
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3479
0
    case ImGuiCol_TextLink: return "TextLink";
3480
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3481
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3482
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3483
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3484
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3485
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3486
0
    }
3487
0
    IM_ASSERT(0);
3488
0
    return "Unknown";
3489
0
}
3490
3491
3492
//-----------------------------------------------------------------------------
3493
// [SECTION] RENDER HELPERS
3494
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3495
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3496
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3497
//-----------------------------------------------------------------------------
3498
3499
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3500
322k
{
3501
322k
    const char* text_display_end = text;
3502
322k
    if (!text_end)
3503
322k
        text_end = (const char*)-1;
3504
3505
2.89M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3506
2.57M
        text_display_end++;
3507
322k
    return text_display_end;
3508
322k
}
3509
3510
// Internal ImGui functions to render text
3511
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3512
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3513
0
{
3514
0
    ImGuiContext& g = *GImGui;
3515
0
    ImGuiWindow* window = g.CurrentWindow;
3516
3517
    // Hide anything after a '##' string
3518
0
    const char* text_display_end;
3519
0
    if (hide_text_after_hash)
3520
0
    {
3521
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3522
0
    }
3523
0
    else
3524
0
    {
3525
0
        if (!text_end)
3526
0
            text_end = text + strlen(text); // FIXME-OPT
3527
0
        text_display_end = text_end;
3528
0
    }
3529
3530
0
    if (text != text_display_end)
3531
0
    {
3532
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3533
0
        if (g.LogEnabled)
3534
0
            LogRenderedText(&pos, text, text_display_end);
3535
0
    }
3536
0
}
3537
3538
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3539
4
{
3540
4
    ImGuiContext& g = *GImGui;
3541
4
    ImGuiWindow* window = g.CurrentWindow;
3542
3543
4
    if (!text_end)
3544
0
        text_end = text + strlen(text); // FIXME-OPT
3545
3546
4
    if (text != text_end)
3547
4
    {
3548
4
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3549
4
        if (g.LogEnabled)
3550
0
            LogRenderedText(&pos, text, text_end);
3551
4
    }
3552
4
}
3553
3554
// Default clip_rect uses (pos_min,pos_max)
3555
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3556
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3557
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3558
// better advantage of the render function taking size into account for coarse clipping.
3559
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3560
161k
{
3561
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3562
161k
    ImVec2 pos = pos_min;
3563
161k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3564
3565
161k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3566
161k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3567
161k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3568
161k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3569
161k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3570
3571
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3572
161k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3573
161k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3574
3575
    // Render
3576
161k
    if (need_clipping)
3577
1
    {
3578
1
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3579
1
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3580
1
    }
3581
161k
    else
3582
161k
    {
3583
161k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3584
161k
    }
3585
161k
}
3586
3587
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3588
161k
{
3589
    // Hide anything after a '##' string
3590
161k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3591
161k
    const int text_len = (int)(text_display_end - text);
3592
161k
    if (text_len == 0)
3593
0
        return;
3594
3595
161k
    ImGuiContext& g = *GImGui;
3596
161k
    ImGuiWindow* window = g.CurrentWindow;
3597
161k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3598
161k
    if (g.LogEnabled)
3599
0
        LogRenderedText(&pos_min, text, text_display_end);
3600
161k
}
3601
3602
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3603
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3604
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3605
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3606
0
{
3607
0
    ImGuiContext& g = *GImGui;
3608
0
    if (text_end_full == NULL)
3609
0
        text_end_full = FindRenderedTextEnd(text);
3610
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3611
3612
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3613
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3614
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3615
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3616
0
    if (text_size.x > pos_max.x - pos_min.x)
3617
0
    {
3618
        // Hello wo...
3619
        // |       |   |
3620
        // min   max   ellipsis_max
3621
        //          <-> this is generally some padding value
3622
3623
0
        const ImFont* font = draw_list->_Data->Font;
3624
0
        const float font_size = draw_list->_Data->FontSize;
3625
0
        const float font_scale = draw_list->_Data->FontScale;
3626
0
        const char* text_end_ellipsis = NULL;
3627
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3628
3629
        // We can now claim the space between pos_max.x and ellipsis_max.x
3630
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3631
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3632
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3633
0
        {
3634
            // Always display at least 1 character if there's no room for character + ellipsis
3635
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3636
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3637
0
        }
3638
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3639
0
        {
3640
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3641
0
            text_end_ellipsis--;
3642
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3643
0
        }
3644
3645
        // Render text, render ellipsis
3646
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3647
0
        ImVec2 ellipsis_pos = ImTrunc(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3648
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3649
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3650
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3651
0
    }
3652
0
    else
3653
0
    {
3654
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3655
0
    }
3656
3657
0
    if (g.LogEnabled)
3658
0
        LogRenderedText(&pos_min, text, text_end_full);
3659
0
}
3660
3661
// Render a rectangle shaped with optional rounding and borders
3662
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3663
55.2k
{
3664
55.2k
    ImGuiContext& g = *GImGui;
3665
55.2k
    ImGuiWindow* window = g.CurrentWindow;
3666
55.2k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3667
55.2k
    const float border_size = g.Style.FrameBorderSize;
3668
55.2k
    if (border && border_size > 0.0f)
3669
55.2k
    {
3670
55.2k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3671
55.2k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3672
55.2k
    }
3673
55.2k
}
3674
3675
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3676
0
{
3677
0
    ImGuiContext& g = *GImGui;
3678
0
    ImGuiWindow* window = g.CurrentWindow;
3679
0
    const float border_size = g.Style.FrameBorderSize;
3680
0
    if (border_size > 0.0f)
3681
0
    {
3682
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3683
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3684
0
    }
3685
0
}
3686
3687
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3688
195k
{
3689
195k
    ImGuiContext& g = *GImGui;
3690
195k
    if (id != g.NavId)
3691
169k
        return;
3692
25.5k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3693
5.26k
        return;
3694
20.2k
    ImGuiWindow* window = g.CurrentWindow;
3695
20.2k
    if (window->DC.NavHideHighlightOneFrame)
3696
0
        return;
3697
3698
20.2k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3699
20.2k
    ImRect display_rect = bb;
3700
20.2k
    display_rect.ClipWith(window->ClipRect);
3701
20.2k
    const float thickness = 2.0f;
3702
20.2k
    if (flags & ImGuiNavHighlightFlags_Compact)
3703
20.0k
    {
3704
20.0k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3705
20.0k
    }
3706
201
    else
3707
201
    {
3708
201
        const float distance = 3.0f + thickness * 0.5f;
3709
201
        display_rect.Expand(ImVec2(distance, distance));
3710
201
        bool fully_visible = window->ClipRect.Contains(display_rect);
3711
201
        if (!fully_visible)
3712
43
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3713
201
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, thickness);
3714
201
        if (!fully_visible)
3715
43
            window->DrawList->PopClipRect();
3716
201
    }
3717
20.2k
}
3718
3719
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3720
0
{
3721
0
    ImGuiContext& g = *GImGui;
3722
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3723
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3724
0
    for (ImGuiViewportP* viewport : g.Viewports)
3725
0
    {
3726
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3727
0
        ImVec2 offset, size, uv[4];
3728
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3729
0
            continue;
3730
0
        const ImVec2 pos = base_pos - offset;
3731
0
        const float scale = base_scale * viewport->DpiScale;
3732
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3733
0
            continue;
3734
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3735
0
        ImTextureID tex_id = font_atlas->TexID;
3736
0
        draw_list->PushTextureID(tex_id);
3737
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3738
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3739
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3740
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3741
0
        draw_list->PopTextureID();
3742
0
    }
3743
0
}
3744
3745
//-----------------------------------------------------------------------------
3746
// [SECTION] INITIALIZATION, SHUTDOWN
3747
//-----------------------------------------------------------------------------
3748
3749
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3750
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3751
ImGuiContext* ImGui::GetCurrentContext()
3752
1
{
3753
1
    return GImGui;
3754
1
}
3755
3756
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3757
1
{
3758
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3759
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3760
#else
3761
1
    GImGui = ctx;
3762
1
#endif
3763
1
}
3764
3765
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3766
0
{
3767
0
    GImAllocatorAllocFunc = alloc_func;
3768
0
    GImAllocatorFreeFunc = free_func;
3769
0
    GImAllocatorUserData = user_data;
3770
0
}
3771
3772
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3773
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3774
0
{
3775
0
    *p_alloc_func = GImAllocatorAllocFunc;
3776
0
    *p_free_func = GImAllocatorFreeFunc;
3777
0
    *p_user_data = GImAllocatorUserData;
3778
0
}
3779
3780
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3781
1
{
3782
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3783
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3784
1
    SetCurrentContext(ctx);
3785
1
    Initialize();
3786
1
    if (prev_ctx != NULL)
3787
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3788
1
    return ctx;
3789
1
}
3790
3791
void ImGui::DestroyContext(ImGuiContext* ctx)
3792
0
{
3793
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3794
0
    if (ctx == NULL) //-V1051
3795
0
        ctx = prev_ctx;
3796
0
    SetCurrentContext(ctx);
3797
0
    Shutdown();
3798
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3799
0
    IM_DELETE(ctx);
3800
0
}
3801
3802
// IMPORTANT: ###xxx suffixes must be same in ALL languages to allow for automation.
3803
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3804
{
3805
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3806
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3807
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3808
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3809
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3810
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3811
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3812
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3813
    { ImGuiLocKey_CopyLink,             "Copy Link###CopyLink"                  },
3814
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3815
    { ImGuiLocKey_DockingHoldShiftToDock,       "Hold SHIFT to enable Docking window."  },
3816
    { ImGuiLocKey_DockingDragToUndockOrMoveNode,"Click and drag to move or undock whole node."    },
3817
};
3818
3819
void ImGui::Initialize()
3820
1
{
3821
1
    ImGuiContext& g = *GImGui;
3822
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3823
3824
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3825
1
    {
3826
1
        ImGuiSettingsHandler ini_handler;
3827
1
        ini_handler.TypeName = "Window";
3828
1
        ini_handler.TypeHash = ImHashStr("Window");
3829
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3830
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3831
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3832
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3833
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3834
1
        AddSettingsHandler(&ini_handler);
3835
1
    }
3836
1
    TableSettingsAddSettingsHandler();
3837
3838
    // Setup default localization table
3839
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3840
3841
    // Setup default platform clipboard/IME handlers.
3842
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3843
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3844
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3845
1
    g.IO.PlatformOpenInShellFn = PlatformOpenInShellFn_DefaultImpl;
3846
1
    g.IO.PlatformSetImeDataFn = PlatformSetImeDataFn_DefaultImpl;
3847
3848
    // Create default viewport
3849
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3850
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3851
1
    viewport->Idx = 0;
3852
1
    viewport->PlatformWindowCreated = true;
3853
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3854
1
    g.Viewports.push_back(viewport);
3855
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3856
1
    g.ViewportCreatedCount++;
3857
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3858
3859
    // Build KeysMayBeCharInput[] lookup table (1 bool per named key)
3860
155
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
3861
154
        if ((key >= ImGuiKey_0 && key <= ImGuiKey_9) || (key >= ImGuiKey_A && key <= ImGuiKey_Z) || (key >= ImGuiKey_Keypad0 && key <= ImGuiKey_Keypad9)
3862
154
            || key == ImGuiKey_Tab || key == ImGuiKey_Space || key == ImGuiKey_Apostrophe || key == ImGuiKey_Comma || key == ImGuiKey_Minus || key == ImGuiKey_Period
3863
154
            || key == ImGuiKey_Slash || key == ImGuiKey_Semicolon || key == ImGuiKey_Equal || key == ImGuiKey_LeftBracket || key == ImGuiKey_RightBracket || key == ImGuiKey_GraveAccent
3864
154
            || key == ImGuiKey_KeypadDecimal || key == ImGuiKey_KeypadDivide || key == ImGuiKey_KeypadMultiply || key == ImGuiKey_KeypadSubtract || key == ImGuiKey_KeypadAdd || key == ImGuiKey_KeypadEqual)
3865
64
            g.KeysMayBeCharInput.SetBit(key);
3866
3867
1
#ifdef IMGUI_HAS_DOCK
3868
    // Initialize Docking
3869
1
    DockContextInitialize(&g);
3870
1
#endif
3871
3872
1
    g.Initialized = true;
3873
1
}
3874
3875
// This function is merely here to free heap allocations.
3876
void ImGui::Shutdown()
3877
0
{
3878
0
    ImGuiContext& g = *GImGui;
3879
0
    IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == NULL, "Forgot to shutdown Platform backend?");
3880
0
    IM_ASSERT_USER_ERROR(g.IO.BackendRendererUserData == NULL, "Forgot to shutdown Renderer backend?");
3881
3882
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3883
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3884
0
    {
3885
0
        g.IO.Fonts->Locked = false;
3886
0
        IM_DELETE(g.IO.Fonts);
3887
0
    }
3888
0
    g.IO.Fonts = NULL;
3889
0
    g.DrawListSharedData.TempBuffer.clear();
3890
3891
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3892
0
    if (!g.Initialized)
3893
0
        return;
3894
3895
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3896
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3897
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3898
3899
    // Destroy platform windows
3900
0
    DestroyPlatformWindows();
3901
3902
    // Shutdown extensions
3903
0
    DockContextShutdown(&g);
3904
3905
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3906
3907
    // Clear everything else
3908
0
    g.Windows.clear_delete();
3909
0
    g.WindowsFocusOrder.clear();
3910
0
    g.WindowsTempSortBuffer.clear();
3911
0
    g.CurrentWindow = NULL;
3912
0
    g.CurrentWindowStack.clear();
3913
0
    g.WindowsById.Clear();
3914
0
    g.NavWindow = NULL;
3915
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3916
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3917
0
    g.MovingWindow = NULL;
3918
3919
0
    g.KeysRoutingTable.Clear();
3920
3921
0
    g.ColorStack.clear();
3922
0
    g.StyleVarStack.clear();
3923
0
    g.FontStack.clear();
3924
0
    g.OpenPopupStack.clear();
3925
0
    g.BeginPopupStack.clear();
3926
0
    g.TreeNodeStack.clear();
3927
3928
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3929
0
    g.Viewports.clear_delete();
3930
3931
0
    g.TabBars.Clear();
3932
0
    g.CurrentTabBarStack.clear();
3933
0
    g.ShrinkWidthBuffer.clear();
3934
3935
0
    g.ClipperTempData.clear_destruct();
3936
3937
0
    g.Tables.Clear();
3938
0
    g.TablesTempData.clear_destruct();
3939
0
    g.DrawChannelsTempMergeBuffer.clear();
3940
3941
0
    g.MultiSelectStorage.Clear();
3942
0
    g.MultiSelectTempData.clear_destruct();
3943
3944
0
    g.ClipboardHandlerData.clear();
3945
0
    g.MenusIdSubmittedThisFrame.clear();
3946
0
    g.InputTextState.ClearFreeMemory();
3947
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3948
3949
0
    g.SettingsWindows.clear();
3950
0
    g.SettingsHandlers.clear();
3951
3952
0
    if (g.LogFile)
3953
0
    {
3954
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3955
0
        if (g.LogFile != stdout)
3956
0
#endif
3957
0
            ImFileClose(g.LogFile);
3958
0
        g.LogFile = NULL;
3959
0
    }
3960
0
    g.LogBuffer.clear();
3961
0
    g.DebugLogBuf.clear();
3962
0
    g.DebugLogIndex.clear();
3963
3964
0
    g.Initialized = false;
3965
0
}
3966
3967
// No specific ordering/dependency support, will see as needed
3968
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3969
0
{
3970
0
    ImGuiContext& g = *ctx;
3971
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3972
0
    g.Hooks.push_back(*hook);
3973
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3974
0
    return g.HookIdNext;
3975
0
}
3976
3977
// Deferred removal, avoiding issue with changing vector while iterating it
3978
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3979
0
{
3980
0
    ImGuiContext& g = *ctx;
3981
0
    IM_ASSERT(hook_id != 0);
3982
0
    for (ImGuiContextHook& hook : g.Hooks)
3983
0
        if (hook.HookId == hook_id)
3984
0
            hook.Type = ImGuiContextHookType_PendingRemoval_;
3985
0
}
3986
3987
// Call context hooks (used by e.g. test engine)
3988
// We assume a small number of hooks so all stored in same array
3989
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3990
483k
{
3991
483k
    ImGuiContext& g = *ctx;
3992
483k
    for (ImGuiContextHook& hook : g.Hooks)
3993
0
        if (hook.Type == hook_type)
3994
0
            hook.Callback(&g, &hook);
3995
483k
}
3996
3997
3998
//-----------------------------------------------------------------------------
3999
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
4000
//-----------------------------------------------------------------------------
4001
4002
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
4003
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
4004
4
{
4005
4
    memset(this, 0, sizeof(*this));
4006
4
    Ctx = ctx;
4007
4
    Name = ImStrdup(name);
4008
4
    NameBufLen = (int)strlen(name) + 1;
4009
4
    ID = ImHashStr(name);
4010
4
    IDStack.push_back(ID);
4011
4
    ViewportAllowPlatformMonitorExtend = -1;
4012
4
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
4013
4
    MoveId = GetID("#MOVE");
4014
4
    TabId = GetID("#TAB");
4015
4
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
4016
4
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
4017
4
    AutoFitFramesX = AutoFitFramesY = -1;
4018
4
    AutoPosLastDirection = ImGuiDir_None;
4019
4
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
4020
4
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
4021
4
    LastFrameActive = -1;
4022
4
    LastFrameJustFocused = -1;
4023
4
    LastTimeActive = -1.0f;
4024
4
    FontWindowScale = FontDpiScale = 1.0f;
4025
4
    SettingsOffset = -1;
4026
4
    DockOrder = -1;
4027
4
    DrawList = &DrawListInst;
4028
4
    DrawList->_Data = &Ctx->DrawListSharedData;
4029
4
    DrawList->_OwnerName = Name;
4030
4
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
4031
4
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
4032
4
}
4033
4034
ImGuiWindow::~ImGuiWindow()
4035
0
{
4036
0
    IM_ASSERT(DrawList == &DrawListInst);
4037
0
    IM_DELETE(Name);
4038
0
    ColumnsStorage.clear_destruct();
4039
0
}
4040
4041
static void SetCurrentWindow(ImGuiWindow* window)
4042
372k
{
4043
372k
    ImGuiContext& g = *GImGui;
4044
372k
    g.CurrentWindow = window;
4045
372k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
4046
372k
    if (window)
4047
292k
    {
4048
292k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
4049
292k
        g.FontScale = g.FontSize / g.Font->FontSize;
4050
292k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
4051
292k
    }
4052
372k
}
4053
4054
void ImGui::GcCompactTransientMiscBuffers()
4055
0
{
4056
0
    ImGuiContext& g = *GImGui;
4057
0
    g.ItemFlagsStack.clear();
4058
0
    g.GroupStack.clear();
4059
0
    g.MultiSelectTempDataStacked = 0;
4060
0
    g.MultiSelectTempData.clear_destruct();
4061
0
    TableGcCompactSettings();
4062
0
}
4063
4064
// Free up/compact internal window buffers, we can use this when a window becomes unused.
4065
// Not freed:
4066
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
4067
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
4068
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
4069
4
{
4070
4
    window->MemoryCompacted = true;
4071
4
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
4072
4
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
4073
4
    window->IDStack.clear();
4074
4
    window->DrawList->_ClearFreeMemory();
4075
4
    window->DC.ChildWindows.clear();
4076
4
    window->DC.ItemWidthStack.clear();
4077
4
    window->DC.TextWrapPosStack.clear();
4078
4
}
4079
4080
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
4081
3
{
4082
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
4083
    // The other buffers tends to amortize much faster.
4084
3
    window->MemoryCompacted = false;
4085
3
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
4086
3
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
4087
3
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
4088
3
}
4089
4090
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
4091
638
{
4092
638
    ImGuiContext& g = *GImGui;
4093
4094
    // Clear previous active id
4095
638
    if (g.ActiveId != 0)
4096
260
    {
4097
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
4098
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
4099
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
4100
260
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
4101
0
        {
4102
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
4103
0
            g.MovingWindow = NULL;
4104
0
        }
4105
4106
        // This could be written in a more general way (e.g associate a hook to ActiveId),
4107
        // but since this is currently quite an exception we'll leave it as is.
4108
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
4109
260
        if (g.InputTextState.ID == g.ActiveId)
4110
0
            InputTextDeactivateHook(g.ActiveId);
4111
260
    }
4112
4113
    // Set active id
4114
638
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
4115
638
    if (g.ActiveIdIsJustActivated)
4116
521
    {
4117
521
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
4118
521
        g.ActiveIdTimer = 0.0f;
4119
521
        g.ActiveIdHasBeenPressedBefore = false;
4120
521
        g.ActiveIdHasBeenEditedBefore = false;
4121
521
        g.ActiveIdMouseButton = -1;
4122
521
        if (id != 0)
4123
261
        {
4124
261
            g.LastActiveId = id;
4125
261
            g.LastActiveIdTimer = 0.0f;
4126
261
        }
4127
521
    }
4128
638
    g.ActiveId = id;
4129
638
    g.ActiveIdAllowOverlap = false;
4130
638
    g.ActiveIdNoClearOnFocusLoss = false;
4131
638
    g.ActiveIdWindow = window;
4132
638
    g.ActiveIdHasBeenEditedThisFrame = false;
4133
638
    g.ActiveIdFromShortcut = false;
4134
638
    if (id)
4135
261
    {
4136
261
        g.ActiveIdIsAlive = id;
4137
261
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
4138
261
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
4139
261
    }
4140
4141
    // Clear declaration of inputs claimed by the widget
4142
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
4143
638
    g.ActiveIdUsingNavDirMask = 0x00;
4144
638
    g.ActiveIdUsingAllKeyboardKeys = false;
4145
638
}
4146
4147
void ImGui::ClearActiveID()
4148
377
{
4149
377
    SetActiveID(0, NULL); // g.ActiveId = 0;
4150
377
}
4151
4152
void ImGui::SetHoveredID(ImGuiID id)
4153
1.30k
{
4154
1.30k
    ImGuiContext& g = *GImGui;
4155
1.30k
    g.HoveredId = id;
4156
1.30k
    g.HoveredIdAllowOverlap = false;
4157
1.30k
    if (id != 0 && g.HoveredIdPreviousFrame != id)
4158
21
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
4159
1.30k
}
4160
4161
ImGuiID ImGui::GetHoveredID()
4162
0
{
4163
0
    ImGuiContext& g = *GImGui;
4164
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
4165
0
}
4166
4167
void ImGui::MarkItemEdited(ImGuiID id)
4168
0
{
4169
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
4170
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
4171
0
    ImGuiContext& g = *GImGui;
4172
0
    if (g.LockMarkEdited > 0)
4173
0
        return;
4174
0
    if (g.ActiveId == id || g.ActiveId == 0)
4175
0
    {
4176
0
        g.ActiveIdHasBeenEditedThisFrame = true;
4177
0
        g.ActiveIdHasBeenEditedBefore = true;
4178
0
    }
4179
4180
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
4181
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
4182
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id || (g.CurrentMultiSelect != NULL && g.BoxSelectState.IsActive));
4183
4184
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4185
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4186
0
}
4187
4188
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4189
1.40k
{
4190
    // An active popup disable hovering on other windows (apart from its own children)
4191
    // FIXME-OPT: This could be cached/stored within the window.
4192
1.40k
    ImGuiContext& g = *GImGui;
4193
1.40k
    if (g.NavWindow)
4194
1.17k
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4195
1.17k
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4196
0
            {
4197
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4198
                // NB: The 'else' is important because Modal windows are also Popups.
4199
0
                bool want_inhibit = false;
4200
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4201
0
                    want_inhibit = true;
4202
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4203
0
                    want_inhibit = true;
4204
4205
                // Inhibit hover unless the window is within the stack of our modal/popup
4206
0
                if (want_inhibit)
4207
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4208
0
                        return false;
4209
0
            }
4210
4211
    // Filter by viewport
4212
1.40k
    if (window->Viewport != g.MouseViewport)
4213
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4214
0
            return false;
4215
4216
1.40k
    return true;
4217
1.40k
}
4218
4219
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4220
0
{
4221
0
    ImGuiContext& g = *GImGui;
4222
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4223
0
        return g.Style.HoverDelayNormal;
4224
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4225
0
        return g.Style.HoverDelayShort;
4226
0
    return 0.0f;
4227
0
}
4228
4229
static ImGuiHoveredFlags ApplyHoverFlagsForTooltip(ImGuiHoveredFlags user_flags, ImGuiHoveredFlags shared_flags)
4230
0
{
4231
    // Allow instance flags to override shared flags
4232
0
    if (user_flags & (ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal))
4233
0
        shared_flags &= ~(ImGuiHoveredFlags_DelayNone | ImGuiHoveredFlags_DelayShort | ImGuiHoveredFlags_DelayNormal);
4234
0
    return user_flags | shared_flags;
4235
0
}
4236
4237
// This is roughly matching the behavior of internal-facing ItemHoverable()
4238
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4239
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4240
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4241
0
{
4242
0
    ImGuiContext& g = *GImGui;
4243
0
    ImGuiWindow* window = g.CurrentWindow;
4244
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4245
4246
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4247
0
    {
4248
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4249
0
            return false;
4250
0
        if (!IsItemFocused())
4251
0
            return false;
4252
4253
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4254
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav);
4255
0
    }
4256
0
    else
4257
0
    {
4258
        // Test for bounding box overlap, as updated as ItemAdd()
4259
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4260
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4261
0
            return false;
4262
4263
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4264
0
            flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
4265
4266
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4267
4268
        // Done with rectangle culling so we can perform heavier checks now
4269
        // Test if we are hovering the right window (our window could be behind another window)
4270
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4271
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4272
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4273
        // the test that has been running for a long while.
4274
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4275
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4276
0
                return false;
4277
4278
        // Test if another item is active (e.g. being dragged)
4279
0
        const ImGuiID id = g.LastItemData.ID;
4280
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4281
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4282
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4283
0
                    return false;
4284
4285
        // Test if interactions on this window are blocked by an active popup or modal.
4286
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4287
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4288
0
            return false;
4289
4290
        // Test if the item is disabled
4291
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4292
0
            return false;
4293
4294
        // Special handling for calling after Begin() which represent the title bar or tab.
4295
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4296
        // will never be overwritten so we need to detect the case.
4297
0
        if (id == window->MoveId && window->WriteAccessed)
4298
0
            return false;
4299
4300
        // Test if using AllowOverlap and overlapped
4301
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_AllowOverlap) && id != 0)
4302
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4303
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4304
0
                    return false;
4305
0
    }
4306
4307
    // Handle hover delay
4308
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4309
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4310
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4311
0
    {
4312
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4313
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4314
0
            g.HoverItemDelayTimer = 0.0f;
4315
0
        g.HoverItemDelayId = hover_delay_id;
4316
4317
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4318
        // but once unlocked on a given item we also moving.
4319
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4320
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4321
0
            return false;
4322
4323
0
        if (g.HoverItemDelayTimer < delay)
4324
0
            return false;
4325
0
    }
4326
4327
0
    return true;
4328
0
}
4329
4330
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4331
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4332
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4333
// If you used this in your legacy/custom widgets code:
4334
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4335
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4336
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4337
323k
{
4338
323k
    ImGuiContext& g = *GImGui;
4339
323k
    ImGuiWindow* window = g.CurrentWindow;
4340
323k
    if (g.HoveredWindow != window)
4341
252k
        return false;
4342
71.5k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4343
70.2k
        return false;
4344
4345
1.30k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4346
0
        return false;
4347
1.30k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4348
0
        if (!g.ActiveIdFromShortcut)
4349
0
            return false;
4350
4351
    // Done with rectangle culling so we can perform heavier checks now.
4352
1.30k
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4353
0
    {
4354
0
        g.HoveredIdIsDisabled = true;
4355
0
        return false;
4356
0
    }
4357
4358
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4359
    // hover test in widgets code. We could also decide to split this function is two.
4360
1.30k
    if (id != 0)
4361
1.30k
    {
4362
        // Drag source doesn't report as hovered
4363
1.30k
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4364
0
            return false;
4365
4366
1.30k
        SetHoveredID(id);
4367
4368
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4369
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4370
1.30k
        if (item_flags & ImGuiItemFlags_AllowOverlap)
4371
0
        {
4372
0
            g.HoveredIdAllowOverlap = true;
4373
0
            if (g.HoveredIdPreviousFrame != id)
4374
0
                return false;
4375
0
        }
4376
4377
        // Display shortcut (only works with mouse)
4378
        // (ImGuiItemStatusFlags_HasShortcut in LastItemData denotes we want a tooltip)
4379
1.30k
        if (id == g.LastItemData.ID && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasShortcut))
4380
0
            if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal))
4381
0
                SetTooltip("%s", GetKeyChordName(g.LastItemData.Shortcut));
4382
1.30k
    }
4383
4384
    // When disabled we'll return false but still set HoveredId
4385
1.30k
    if (item_flags & ImGuiItemFlags_Disabled)
4386
0
    {
4387
        // Release active id if turning disabled
4388
0
        if (g.ActiveId == id && id != 0)
4389
0
            ClearActiveID();
4390
0
        g.HoveredIdIsDisabled = true;
4391
0
        return false;
4392
0
    }
4393
4394
1.30k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4395
1.30k
    if (id != 0)
4396
1.30k
    {
4397
        // [DEBUG] Item Picker tool!
4398
        // We perform the check here because reaching is path is rare (1~ time a frame),
4399
        // making the cost of this tool near-zero! We could get better call-stack and support picking non-hovered
4400
        // items if we performed the test in ItemAdd(), but that would incur a bigger runtime cost.
4401
1.30k
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4402
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4403
1.30k
        if (g.DebugItemPickerBreakId == id)
4404
0
            IM_DEBUG_BREAK();
4405
1.30k
    }
4406
1.30k
#endif
4407
4408
1.30k
    if (g.NavDisableMouseHover)
4409
95
        return false;
4410
4411
1.20k
    return true;
4412
1.30k
}
4413
4414
// FIXME: This is inlined/duplicated in ItemAdd()
4415
// FIXME: The id != 0 path is not used by our codebase, may get rid of it?
4416
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4417
0
{
4418
0
    ImGuiContext& g = *GImGui;
4419
0
    ImGuiWindow* window = g.CurrentWindow;
4420
0
    if (!bb.Overlaps(window->ClipRect))
4421
0
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
4422
0
            if (!g.ItemUnclipByLog)
4423
0
                return true;
4424
0
    return false;
4425
0
}
4426
4427
// This is also inlined in ItemAdd()
4428
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4429
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4430
186k
{
4431
186k
    ImGuiContext& g = *GImGui;
4432
186k
    g.LastItemData.ID = item_id;
4433
186k
    g.LastItemData.InFlags = in_flags;
4434
186k
    g.LastItemData.StatusFlags = item_flags;
4435
186k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4436
186k
}
4437
4438
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4439
0
{
4440
0
    if (wrap_pos_x < 0.0f)
4441
0
        return 0.0f;
4442
4443
0
    ImGuiContext& g = *GImGui;
4444
0
    ImGuiWindow* window = g.CurrentWindow;
4445
0
    if (wrap_pos_x == 0.0f)
4446
0
    {
4447
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4448
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4449
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4450
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4451
        //else
4452
0
        wrap_pos_x = window->WorkRect.Max.x;
4453
0
    }
4454
0
    else if (wrap_pos_x > 0.0f)
4455
0
    {
4456
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4457
0
    }
4458
4459
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4460
0
}
4461
4462
// IM_ALLOC() == ImGui::MemAlloc()
4463
void* ImGui::MemAlloc(size_t size)
4464
1.25k
{
4465
1.25k
    void* ptr = (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4466
1.25k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4467
1.25k
    if (ImGuiContext* ctx = GImGui)
4468
1.25k
        DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, size);
4469
1.25k
#endif
4470
1.25k
    return ptr;
4471
1.25k
}
4472
4473
// IM_FREE() == ImGui::MemFree()
4474
void ImGui::MemFree(void* ptr)
4475
1.20k
{
4476
1.20k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4477
1.20k
    if (ptr != NULL)
4478
1.19k
        if (ImGuiContext* ctx = GImGui)
4479
1.19k
            DebugAllocHook(&ctx->DebugAllocInfo, ctx->FrameCount, ptr, (size_t)-1);
4480
1.20k
#endif
4481
1.20k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4482
1.20k
}
4483
4484
// We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames"
4485
void ImGui::DebugAllocHook(ImGuiDebugAllocInfo* info, int frame_count, void* ptr, size_t size)
4486
2.44k
{
4487
2.44k
    ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4488
2.44k
    IM_UNUSED(ptr);
4489
2.44k
    if (entry->FrameCount != frame_count)
4490
40
    {
4491
40
        info->LastEntriesIdx = (info->LastEntriesIdx + 1) % IM_ARRAYSIZE(info->LastEntriesBuf);
4492
40
        entry = &info->LastEntriesBuf[info->LastEntriesIdx];
4493
40
        entry->FrameCount = frame_count;
4494
40
        entry->AllocCount = entry->FreeCount = 0;
4495
40
    }
4496
2.44k
    if (size != (size_t)-1)
4497
1.25k
    {
4498
1.25k
        entry->AllocCount++;
4499
1.25k
        info->TotalAllocCount++;
4500
        //printf("[%05d] MemAlloc(%d) -> 0x%p\n", frame_count, size, ptr);
4501
1.25k
    }
4502
1.19k
    else
4503
1.19k
    {
4504
1.19k
        entry->FreeCount++;
4505
1.19k
        info->TotalFreeCount++;
4506
        //printf("[%05d] MemFree(0x%p)\n", frame_count, ptr);
4507
1.19k
    }
4508
2.44k
}
4509
4510
const char* ImGui::GetClipboardText()
4511
0
{
4512
0
    ImGuiContext& g = *GImGui;
4513
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4514
0
}
4515
4516
void ImGui::SetClipboardText(const char* text)
4517
0
{
4518
0
    ImGuiContext& g = *GImGui;
4519
0
    if (g.IO.SetClipboardTextFn)
4520
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4521
0
}
4522
4523
const char* ImGui::GetVersion()
4524
0
{
4525
0
    return IMGUI_VERSION;
4526
0
}
4527
4528
ImGuiIO& ImGui::GetIO()
4529
238k
{
4530
238k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4531
238k
    return GImGui->IO;
4532
238k
}
4533
4534
ImGuiPlatformIO& ImGui::GetPlatformIO()
4535
0
{
4536
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext()?");
4537
0
    return GImGui->PlatformIO;
4538
0
}
4539
4540
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4541
ImDrawData* ImGui::GetDrawData()
4542
80.5k
{
4543
80.5k
    ImGuiContext& g = *GImGui;
4544
80.5k
    ImGuiViewportP* viewport = g.Viewports[0];
4545
80.5k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4546
80.5k
}
4547
4548
double ImGui::GetTime()
4549
73
{
4550
73
    return GImGui->Time;
4551
73
}
4552
4553
int ImGui::GetFrameCount()
4554
0
{
4555
0
    return GImGui->FrameCount;
4556
0
}
4557
4558
static ImDrawList* GetViewportBgFgDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4559
0
{
4560
    // Create the draw list on demand, because they are not frequently used for all viewports
4561
0
    ImGuiContext& g = *GImGui;
4562
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->BgFgDrawLists));
4563
0
    ImDrawList* draw_list = viewport->BgFgDrawLists[drawlist_no];
4564
0
    if (draw_list == NULL)
4565
0
    {
4566
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4567
0
        draw_list->_OwnerName = drawlist_name;
4568
0
        viewport->BgFgDrawLists[drawlist_no] = draw_list;
4569
0
    }
4570
4571
    // Our ImDrawList system requires that there is always a command
4572
0
    if (viewport->BgFgDrawListsLastFrame[drawlist_no] != g.FrameCount)
4573
0
    {
4574
0
        draw_list->_ResetForNewFrame();
4575
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4576
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4577
0
        viewport->BgFgDrawListsLastFrame[drawlist_no] = g.FrameCount;
4578
0
    }
4579
0
    return draw_list;
4580
0
}
4581
4582
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4583
0
{
4584
0
    if (viewport == NULL)
4585
0
        viewport = GImGui->CurrentWindow->Viewport;
4586
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4587
0
}
4588
4589
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4590
0
{
4591
0
    if (viewport == NULL)
4592
0
        viewport = GImGui->CurrentWindow->Viewport;
4593
0
    return GetViewportBgFgDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4594
0
}
4595
4596
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4597
0
{
4598
0
    return &GImGui->DrawListSharedData;
4599
0
}
4600
4601
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4602
164
{
4603
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4604
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4605
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4606
164
    ImGuiContext& g = *GImGui;
4607
164
    FocusWindow(window);
4608
164
    SetActiveID(window->MoveId, window);
4609
164
    g.NavDisableHighlight = true;
4610
164
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4611
164
    g.ActiveIdNoClearOnFocusLoss = true;
4612
164
    SetActiveIdUsingAllKeyboardKeys();
4613
4614
164
    bool can_move_window = true;
4615
164
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4616
0
        can_move_window = false;
4617
164
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4618
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4619
0
            can_move_window = false;
4620
164
    if (can_move_window)
4621
164
        g.MovingWindow = window;
4622
164
}
4623
4624
// We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4625
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock)
4626
0
{
4627
0
    ImGuiContext& g = *GImGui;
4628
0
    bool can_undock_node = false;
4629
0
    if (undock && node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0 && (node->MergedFlags & ImGuiDockNodeFlags_NoUndocking) == 0)
4630
0
    {
4631
        // Can undock if:
4632
        // - part of a hierarchy with more than one visible node (if only one is visible, we'll just move the root window)
4633
        // - part of a dockspace node hierarchy: so we can undock the last single visible node too (trivia: undocking from a fixed/central node will create a new node and copy windows)
4634
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4635
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4636
0
            can_undock_node = true;
4637
0
    }
4638
4639
0
    const bool clicked = IsMouseClicked(0);
4640
0
    const bool dragging = IsMouseDragging(0);
4641
0
    if (can_undock_node && dragging)
4642
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4643
0
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4644
0
        StartMouseMovingWindow(window);
4645
0
}
4646
4647
// Handle mouse moving window
4648
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4649
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4650
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4651
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4652
void ImGui::UpdateMouseMovingWindowNewFrame()
4653
80.5k
{
4654
80.5k
    ImGuiContext& g = *GImGui;
4655
80.5k
    if (g.MovingWindow != NULL)
4656
5.13k
    {
4657
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4658
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4659
5.13k
        KeepAliveID(g.ActiveId);
4660
5.13k
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4661
5.13k
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4662
4663
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4664
5.13k
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4665
5.13k
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4666
4.96k
        {
4667
4.96k
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4668
4.96k
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4669
126
            {
4670
126
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4671
126
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4672
0
                {
4673
0
                    moving_window->Viewport->Pos = pos;
4674
0
                    moving_window->Viewport->UpdateWorkRect();
4675
0
                }
4676
126
            }
4677
4.96k
            FocusWindow(g.MovingWindow);
4678
4.96k
        }
4679
163
        else
4680
163
        {
4681
163
            if (!window_disappared)
4682
163
            {
4683
                // Try to merge the window back into the main viewport.
4684
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4685
163
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4686
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4687
4688
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4689
163
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4690
163
                    g.MouseViewport = moving_window->Viewport;
4691
4692
                // Clear the NoInput window flag set by the Viewport system
4693
163
                if (moving_window->Viewport)
4694
163
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4695
163
            }
4696
4697
163
            g.MovingWindow = NULL;
4698
163
            ClearActiveID();
4699
163
        }
4700
5.13k
    }
4701
75.4k
    else
4702
75.4k
    {
4703
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4704
75.4k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4705
0
        {
4706
0
            KeepAliveID(g.ActiveId);
4707
0
            if (!g.IO.MouseDown[0])
4708
0
                ClearActiveID();
4709
0
        }
4710
75.4k
    }
4711
80.5k
}
4712
4713
// Initiate moving window when clicking on empty space or title bar.
4714
// Handle left-click and right-click focus.
4715
void ImGui::UpdateMouseMovingWindowEndFrame()
4716
80.5k
{
4717
80.5k
    ImGuiContext& g = *GImGui;
4718
80.5k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4719
6.29k
        return;
4720
4721
    // Unless we just made a window/popup appear
4722
74.2k
    if (g.NavWindow && g.NavWindow->Appearing)
4723
5
        return;
4724
4725
    // Click on empty space to focus window and start moving
4726
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4727
74.2k
    if (g.IO.MouseClicked[0])
4728
2.76k
    {
4729
        // Handle the edge case of a popup being closed while clicking in its empty space.
4730
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4731
2.76k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4732
2.76k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4733
4734
2.76k
        if (root_window != NULL && !is_closed_popup)
4735
164
        {
4736
164
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4737
4738
            // Cancel moving if clicked outside of title bar
4739
164
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4740
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4741
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4742
0
                        g.MovingWindow = NULL;
4743
4744
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4745
164
            if (g.HoveredIdIsDisabled)
4746
0
                g.MovingWindow = NULL;
4747
164
        }
4748
2.60k
        else if (root_window == NULL && g.NavWindow != NULL)
4749
205
        {
4750
            // Clicking on void disable focus
4751
205
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4752
205
        }
4753
2.76k
    }
4754
4755
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4756
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4757
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4758
74.2k
    if (g.IO.MouseClicked[1])
4759
200
    {
4760
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4761
        // This is where we can trim the popup stack.
4762
200
        ImGuiWindow* modal = GetTopMostPopupModal();
4763
200
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4764
200
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4765
200
    }
4766
74.2k
}
4767
4768
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4769
// Need to keep in sync with SetWindowPos()
4770
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4771
0
{
4772
0
    window->Pos += delta;
4773
0
    window->ClipRect.Translate(delta);
4774
0
    window->OuterRectClipped.Translate(delta);
4775
0
    window->InnerRect.Translate(delta);
4776
0
    window->DC.CursorPos += delta;
4777
0
    window->DC.CursorStartPos += delta;
4778
0
    window->DC.CursorMaxPos += delta;
4779
0
    window->DC.IdealMaxPos += delta;
4780
0
}
4781
4782
static void ScaleWindow(ImGuiWindow* window, float scale)
4783
0
{
4784
0
    ImVec2 origin = window->Viewport->Pos;
4785
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4786
0
    window->Size = ImTrunc(window->Size * scale);
4787
0
    window->SizeFull = ImTrunc(window->SizeFull * scale);
4788
0
    window->ContentSize = ImTrunc(window->ContentSize * scale);
4789
0
}
4790
4791
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4792
318k
{
4793
318k
    return (window->Active) && (!window->Hidden);
4794
318k
}
4795
4796
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4797
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4798
80.5k
{
4799
80.5k
    ImGuiContext& g = *GImGui;
4800
80.5k
    ImGuiIO& io = g.IO;
4801
4802
    // FIXME-DPI: This storage was added on 2021/03/31 for test engine, but if we want to multiply WINDOWS_HOVER_PADDING
4803
    // by DpiScale, we need to make this window-agnostic anyhow, maybe need storing inside ImGuiWindow.
4804
80.5k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4805
4806
    // Find the window hovered by mouse:
4807
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4808
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4809
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4810
80.5k
    bool clear_hovered_windows = false;
4811
80.5k
    FindHoveredWindowEx(g.IO.MousePos, false, &g.HoveredWindow, &g.HoveredWindowUnderMovingWindow);
4812
80.5k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4813
80.5k
    g.HoveredWindowBeforeClear = g.HoveredWindow;
4814
4815
    // Modal windows prevents mouse from hovering behind them.
4816
80.5k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4817
80.5k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4818
0
        clear_hovered_windows = true;
4819
4820
    // Disabled mouse hovering (we don't currently clear MousePos, we could)
4821
80.5k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4822
0
        clear_hovered_windows = true;
4823
4824
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4825
    // won't report hovering nor request capture even while dragging over our windows afterward.
4826
80.5k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4827
80.5k
    const bool has_open_modal = (modal_window != NULL);
4828
80.5k
    int mouse_earliest_down = -1;
4829
80.5k
    bool mouse_any_down = false;
4830
483k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4831
402k
    {
4832
402k
        if (io.MouseClicked[i])
4833
4.55k
        {
4834
4.55k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4835
4.55k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4836
4.55k
        }
4837
402k
        mouse_any_down |= io.MouseDown[i];
4838
402k
        if (io.MouseDown[i] || io.MouseReleased[i]) // Increase release frame for our evaluation of earliest button (#1392)
4839
88.1k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4840
67.5k
                mouse_earliest_down = i;
4841
402k
    }
4842
80.5k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4843
80.5k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4844
4845
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4846
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4847
80.5k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4848
80.5k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4849
47.0k
        clear_hovered_windows = true;
4850
4851
80.5k
    if (clear_hovered_windows)
4852
47.0k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4853
4854
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4855
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4856
80.5k
    if (g.WantCaptureMouseNextFrame != -1)
4857
0
    {
4858
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4859
0
    }
4860
80.5k
    else
4861
80.5k
    {
4862
80.5k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4863
80.5k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4864
80.5k
    }
4865
4866
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4867
80.5k
    io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4868
80.5k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4869
17.5k
        io.WantCaptureKeyboard = true;
4870
80.5k
    if (g.WantCaptureKeyboardNextFrame != -1) // Manual override
4871
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4872
4873
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4874
80.5k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4875
80.5k
}
4876
4877
// Calling SetupDrawListSharedData() is followed by SetCurrentFont() which sets up the remaining data.
4878
static void SetupDrawListSharedData()
4879
80.5k
{
4880
80.5k
    ImGuiContext& g = *GImGui;
4881
80.5k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4882
80.5k
    for (ImGuiViewportP* viewport : g.Viewports)
4883
80.5k
        virtual_space.Add(viewport->GetMainRect());
4884
80.5k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4885
80.5k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4886
80.5k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4887
80.5k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4888
80.5k
    if (g.Style.AntiAliasedLines)
4889
80.5k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4890
80.5k
    if (g.Style.AntiAliasedLinesUseTex && !(g.IO.Fonts->Flags & ImFontAtlasFlags_NoBakedLines))
4891
80.5k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4892
80.5k
    if (g.Style.AntiAliasedFill)
4893
80.5k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4894
80.5k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4895
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4896
80.5k
}
4897
4898
void ImGui::NewFrame()
4899
80.5k
{
4900
80.5k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4901
80.5k
    ImGuiContext& g = *GImGui;
4902
4903
    // Remove pending delete hooks before frame start.
4904
    // This deferred removal avoid issues of removal while iterating the hook vector
4905
80.5k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4906
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4907
0
            g.Hooks.erase(&g.Hooks[n]);
4908
4909
80.5k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4910
4911
    // Check and assert for various common IO and Configuration mistakes
4912
80.5k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4913
80.5k
    ErrorCheckNewFrameSanityChecks();
4914
80.5k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4915
4916
    // Load settings on first frame, save settings when modified (after a delay)
4917
80.5k
    UpdateSettings();
4918
4919
80.5k
    g.Time += g.IO.DeltaTime;
4920
80.5k
    g.WithinFrameScope = true;
4921
80.5k
    g.FrameCount += 1;
4922
80.5k
    g.TooltipOverrideCount = 0;
4923
80.5k
    g.WindowsActiveCount = 0;
4924
80.5k
    g.MenusIdSubmittedThisFrame.resize(0);
4925
4926
    // Calculate frame-rate for the user, as a purely luxurious feature
4927
80.5k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4928
80.5k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4929
80.5k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4930
80.5k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4931
80.5k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4932
4933
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4934
80.5k
    g.InputEventsTrail.resize(0);
4935
80.5k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4936
4937
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4938
80.5k
    UpdateViewportsNewFrame();
4939
4940
    // Setup current font and draw list shared data
4941
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4942
80.5k
    g.IO.Fonts->Locked = true;
4943
80.5k
    SetupDrawListSharedData();
4944
80.5k
    SetCurrentFont(GetDefaultFont());
4945
80.5k
    IM_ASSERT(g.Font->IsLoaded());
4946
4947
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4948
80.5k
    for (ImGuiViewportP* viewport : g.Viewports)
4949
80.5k
    {
4950
80.5k
        viewport->DrawData = NULL;
4951
80.5k
        viewport->DrawDataP.Valid = false;
4952
80.5k
    }
4953
4954
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4955
80.5k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4956
3.48k
        KeepAliveID(g.DragDropPayload.SourceId);
4957
4958
    // Update HoveredId data
4959
80.5k
    if (!g.HoveredIdPreviousFrame)
4960
79.2k
        g.HoveredIdTimer = 0.0f;
4961
80.5k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4962
79.3k
        g.HoveredIdNotActiveTimer = 0.0f;
4963
80.5k
    if (g.HoveredId)
4964
1.30k
        g.HoveredIdTimer += g.IO.DeltaTime;
4965
80.5k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4966
1.14k
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4967
80.5k
    g.HoveredIdPreviousFrame = g.HoveredId;
4968
80.5k
    g.HoveredId = 0;
4969
80.5k
    g.HoveredIdAllowOverlap = false;
4970
80.5k
    g.HoveredIdIsDisabled = false;
4971
4972
    // Clear ActiveID if the item is not alive anymore.
4973
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4974
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4975
80.5k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4976
0
    {
4977
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4978
0
        ClearActiveID();
4979
0
    }
4980
4981
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4982
80.5k
    if (g.ActiveId)
4983
5.31k
        g.ActiveIdTimer += g.IO.DeltaTime;
4984
80.5k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4985
80.5k
    g.ActiveIdPreviousFrame = g.ActiveId;
4986
80.5k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4987
80.5k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4988
80.5k
    g.ActiveIdIsAlive = 0;
4989
80.5k
    g.ActiveIdHasBeenEditedThisFrame = false;
4990
80.5k
    g.ActiveIdPreviousFrameIsAlive = false;
4991
80.5k
    g.ActiveIdIsJustActivated = false;
4992
80.5k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4993
0
        g.TempInputId = 0;
4994
80.5k
    if (g.ActiveId == 0)
4995
75.2k
    {
4996
75.2k
        g.ActiveIdUsingNavDirMask = 0x00;
4997
75.2k
        g.ActiveIdUsingAllKeyboardKeys = false;
4998
75.2k
    }
4999
5000
    // Record when we have been stationary as this state is preserved while over same item.
5001
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
5002
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
5003
80.5k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5004
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
5005
80.5k
    else if (g.HoverItemDelayId == 0)
5006
80.5k
        g.HoverItemUnlockedStationaryId = 0;
5007
80.5k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
5008
12.4k
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
5009
68.0k
    else if (g.HoveredWindow == NULL)
5010
66.7k
        g.HoverWindowUnlockedStationaryId = 0;
5011
5012
    // Update hover delay for IsItemHovered() with delays and tooltips
5013
80.5k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
5014
80.5k
    if (g.HoverItemDelayId != 0)
5015
0
    {
5016
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
5017
0
        g.HoverItemDelayClearTimer = 0.0f;
5018
0
        g.HoverItemDelayId = 0;
5019
0
    }
5020
80.5k
    else if (g.HoverItemDelayTimer > 0.0f)
5021
0
    {
5022
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
5023
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
5024
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
5025
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
5026
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
5027
0
    }
5028
5029
    // Drag and drop
5030
80.5k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
5031
80.5k
    g.DragDropAcceptIdCurr = 0;
5032
80.5k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
5033
80.5k
    g.DragDropWithinSource = false;
5034
80.5k
    g.DragDropWithinTarget = false;
5035
80.5k
    g.DragDropHoldJustPressedId = 0;
5036
5037
    // Close popups on focus lost (currently wip/opt-in)
5038
    //if (g.IO.AppFocusLost)
5039
    //    ClosePopupsExceptModals();
5040
5041
    // Update keyboard input state
5042
80.5k
    UpdateKeyboardInputs();
5043
5044
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
5045
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
5046
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
5047
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
5048
5049
    // Update gamepad/keyboard navigation
5050
80.5k
    NavUpdate();
5051
5052
    // Update mouse input state
5053
80.5k
    UpdateMouseInputs();
5054
5055
    // Undocking
5056
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
5057
80.5k
    DockContextNewFrameUpdateUndocking(&g);
5058
5059
    // Find hovered window
5060
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
5061
80.5k
    UpdateHoveredWindowAndCaptureFlags();
5062
5063
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
5064
80.5k
    UpdateMouseMovingWindowNewFrame();
5065
5066
    // Background darkening/whitening
5067
80.5k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
5068
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
5069
80.5k
    else
5070
80.5k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
5071
5072
80.5k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
5073
80.5k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
5074
5075
    // Platform IME data: reset for the frame
5076
80.5k
    g.PlatformImeDataPrev = g.PlatformImeData;
5077
80.5k
    g.PlatformImeData.WantVisible = false;
5078
5079
    // Mouse wheel scrolling, scale
5080
80.5k
    UpdateMouseWheel();
5081
5082
    // Mark all windows as not visible and compact unused memory.
5083
80.5k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
5084
80.5k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
5085
80.5k
    for (ImGuiWindow* window : g.Windows)
5086
292k
    {
5087
292k
        window->WasActive = window->Active;
5088
292k
        window->Active = false;
5089
292k
        window->WriteAccessed = false;
5090
292k
        window->BeginCountPreviousFrame = window->BeginCount;
5091
292k
        window->BeginCount = 0;
5092
5093
        // Garbage collect transient buffers of recently unused windows
5094
292k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
5095
4
            GcCompactTransientWindowBuffers(window);
5096
292k
    }
5097
5098
    // Garbage collect transient buffers of recently unused tables
5099
80.5k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
5100
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
5101
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
5102
80.5k
    for (ImGuiTableTempData& table_temp_data : g.TablesTempData)
5103
0
        if (table_temp_data.LastTimeActive >= 0.0f && table_temp_data.LastTimeActive < memory_compact_start_time)
5104
0
            TableGcCompactTransientBuffers(&table_temp_data);
5105
80.5k
    if (g.GcCompactAll)
5106
0
        GcCompactTransientMiscBuffers();
5107
80.5k
    g.GcCompactAll = false;
5108
5109
    // Closing the focused window restore focus to the first active root window in descending z-order
5110
80.5k
    if (g.NavWindow && !g.NavWindow->WasActive)
5111
1
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
5112
5113
    // No window should be open at the beginning of the frame.
5114
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
5115
80.5k
    g.CurrentWindowStack.resize(0);
5116
80.5k
    g.BeginPopupStack.resize(0);
5117
80.5k
    g.ItemFlagsStack.resize(0);
5118
80.5k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_AutoClosePopups); // Default flags
5119
80.5k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
5120
80.5k
    g.GroupStack.resize(0);
5121
5122
    // Docking
5123
80.5k
    DockContextNewFrameUpdateDocking(&g);
5124
5125
    // [DEBUG] Update debug features
5126
80.5k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5127
80.5k
    UpdateDebugToolItemPicker();
5128
80.5k
    UpdateDebugToolStackQueries();
5129
80.5k
    UpdateDebugToolFlashStyleColor();
5130
80.5k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
5131
0
    {
5132
0
        g.DebugLocateId = 0;
5133
0
        g.DebugBreakInLocateId = false;
5134
0
    }
5135
80.5k
    if (g.DebugLogAutoDisableFrames > 0 && --g.DebugLogAutoDisableFrames == 0)
5136
0
    {
5137
0
        DebugLog("(Debug Log: Auto-disabled some ImGuiDebugLogFlags after 2 frames)\n");
5138
0
        g.DebugLogFlags &= ~g.DebugLogAutoDisableFlags;
5139
0
        g.DebugLogAutoDisableFlags = ImGuiDebugLogFlags_None;
5140
0
    }
5141
80.5k
#endif
5142
5143
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
5144
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
5145
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
5146
80.5k
    g.WithinFrameScopeWithImplicitWindow = true;
5147
80.5k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
5148
80.5k
    Begin("Debug##Default");
5149
80.5k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
5150
5151
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
5152
    // allowing to validate correct Begin/End behavior in user code.
5153
80.5k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
5154
80.5k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
5155
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
5156
80.5k
    else
5157
80.5k
        g.DebugBeginReturnValueCullDepth = -1;
5158
80.5k
#endif
5159
5160
80.5k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
5161
80.5k
}
5162
5163
// FIXME: Add a more explicit sort order in the window structure.
5164
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
5165
0
{
5166
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
5167
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
5168
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
5169
0
        return d;
5170
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
5171
0
        return d;
5172
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
5173
0
}
5174
5175
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
5176
292k
{
5177
292k
    out_sorted_windows->push_back(window);
5178
292k
    if (window->Active)
5179
105k
    {
5180
105k
        int count = window->DC.ChildWindows.Size;
5181
105k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
5182
131k
        for (int i = 0; i < count; i++)
5183
25.3k
        {
5184
25.3k
            ImGuiWindow* child = window->DC.ChildWindows[i];
5185
25.3k
            if (child->Active)
5186
25.3k
                AddWindowToSortBuffer(out_sorted_windows, child);
5187
25.3k
        }
5188
105k
    }
5189
292k
}
5190
5191
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5192
105k
{
5193
105k
    ImGuiContext& g = *GImGui;
5194
105k
    ImGuiViewportP* viewport = window->Viewport;
5195
105k
    IM_ASSERT(viewport != NULL);
5196
105k
    g.IO.MetricsRenderWindows++;
5197
105k
    if (window->DrawList->_Splitter._Count > 1)
5198
0
        window->DrawList->ChannelsMerge(); // Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags_DockNodeHost windows.
5199
105k
    ImGui::AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5200
105k
    for (ImGuiWindow* child : window->DC.ChildWindows)
5201
25.3k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5202
25.0k
            AddWindowToDrawData(child, layer);
5203
105k
}
5204
5205
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5206
80.5k
{
5207
80.5k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5208
80.5k
}
5209
5210
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5211
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5212
80.5k
{
5213
80.5k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5214
80.5k
}
5215
5216
static void FlattenDrawDataIntoSingleLayer(ImDrawDataBuilder* builder)
5217
80.5k
{
5218
80.5k
    int n = builder->Layers[0]->Size;
5219
80.5k
    int full_size = n;
5220
161k
    for (int i = 1; i < IM_ARRAYSIZE(builder->Layers); i++)
5221
80.5k
        full_size += builder->Layers[i]->Size;
5222
80.5k
    builder->Layers[0]->resize(full_size);
5223
161k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(builder->Layers); layer_n++)
5224
80.5k
    {
5225
80.5k
        ImVector<ImDrawList*>* layer = builder->Layers[layer_n];
5226
80.5k
        if (layer->empty())
5227
80.5k
            continue;
5228
1
        memcpy(builder->Layers[0]->Data + n, layer->Data, layer->Size * sizeof(ImDrawList*));
5229
1
        n += layer->Size;
5230
1
        layer->resize(0);
5231
1
    }
5232
80.5k
}
5233
5234
static void InitViewportDrawData(ImGuiViewportP* viewport)
5235
80.5k
{
5236
80.5k
    ImGuiIO& io = ImGui::GetIO();
5237
80.5k
    ImDrawData* draw_data = &viewport->DrawDataP;
5238
5239
80.5k
    viewport->DrawData = draw_data; // Make publicly accessible
5240
80.5k
    viewport->DrawDataBuilder.Layers[0] = &draw_data->CmdLists;
5241
80.5k
    viewport->DrawDataBuilder.Layers[1] = &viewport->DrawDataBuilder.LayerData1;
5242
80.5k
    viewport->DrawDataBuilder.Layers[0]->resize(0);
5243
80.5k
    viewport->DrawDataBuilder.Layers[1]->resize(0);
5244
5245
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5246
    // and to allow applications/backends to easily skip rendering.
5247
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5248
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5249
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5250
80.5k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5251
5252
80.5k
    draw_data->Valid = true;
5253
80.5k
    draw_data->CmdListsCount = 0;
5254
80.5k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5255
80.5k
    draw_data->DisplayPos = viewport->Pos;
5256
80.5k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5257
80.5k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5258
80.5k
    draw_data->OwnerViewport = viewport;
5259
80.5k
}
5260
5261
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5262
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5263
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5264
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5265
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5266
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5267
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5268
372k
{
5269
372k
    ImGuiWindow* window = GetCurrentWindow();
5270
372k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5271
372k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5272
372k
}
5273
5274
void ImGui::PopClipRect()
5275
186k
{
5276
186k
    ImGuiWindow* window = GetCurrentWindow();
5277
186k
    window->DrawList->PopClipRect();
5278
186k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5279
186k
}
5280
5281
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5282
0
{
5283
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5284
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5285
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5286
0
    return window;
5287
0
}
5288
5289
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5290
0
{
5291
0
    if ((col & IM_COL32_A_MASK) == 0)
5292
0
        return;
5293
5294
0
    ImGuiViewportP* viewport = window->Viewport;
5295
0
    ImRect viewport_rect = viewport->GetMainRect();
5296
5297
    // Draw behind window by moving the draw command at the FRONT of the draw list
5298
0
    {
5299
        // Draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5300
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5301
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5302
0
        draw_list->ChannelsMerge();
5303
0
        if (draw_list->CmdBuffer.Size == 0)
5304
0
            draw_list->AddDrawCmd();
5305
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // FIXME: Need to stricty ensure ImDrawCmd are not merged (ElemCount==6 checks below will verify that)
5306
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5307
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5308
0
        IM_ASSERT(cmd.ElemCount == 6);
5309
0
        draw_list->CmdBuffer.pop_back();
5310
0
        draw_list->CmdBuffer.push_front(cmd);
5311
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5312
0
        draw_list->PopClipRect();
5313
0
    }
5314
5315
    // Draw over sibling docking nodes in a same docking tree
5316
0
    if (window->RootWindow->DockIsActive)
5317
0
    {
5318
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5319
0
        draw_list->ChannelsMerge();
5320
0
        if (draw_list->CmdBuffer.Size == 0)
5321
0
            draw_list->AddDrawCmd();
5322
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5323
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5324
0
        draw_list->PopClipRect();
5325
0
    }
5326
0
}
5327
5328
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5329
0
{
5330
0
    ImGuiContext& g = *GImGui;
5331
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5332
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5333
0
    {
5334
0
        ImGuiWindow* window = g.Windows[i];
5335
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5336
0
            continue;
5337
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5338
0
            break;
5339
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5340
0
            bottom_most_visible_window = window;
5341
0
    }
5342
0
    return bottom_most_visible_window;
5343
0
}
5344
5345
// Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList->ChannelsMerge() before usage.
5346
// We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds().
5347
static void ImGui::RenderDimmedBackgrounds()
5348
80.5k
{
5349
80.5k
    ImGuiContext& g = *GImGui;
5350
80.5k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5351
80.5k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5352
80.5k
        return;
5353
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5354
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5355
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5356
0
        return;
5357
5358
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5359
0
    if (dim_bg_for_modal)
5360
0
    {
5361
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5362
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5363
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(modal_window->DC.ModalDimBgColor, g.DimBgRatio));
5364
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5365
0
    }
5366
0
    else if (dim_bg_for_window_list)
5367
0
    {
5368
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5369
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5370
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5371
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5372
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5373
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5374
5375
        // Draw border around CTRL+Tab target window
5376
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5377
0
        ImGuiViewport* viewport = window->Viewport;
5378
0
        float distance = g.FontSize;
5379
0
        ImRect bb = window->Rect();
5380
0
        bb.Expand(distance);
5381
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5382
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5383
0
        window->DrawList->ChannelsMerge();
5384
0
        if (window->DrawList->CmdBuffer.Size == 0)
5385
0
            window->DrawList->AddDrawCmd();
5386
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5387
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5388
0
        window->DrawList->PopClipRect();
5389
0
    }
5390
5391
    // Draw dimming background on _other_ viewports than the ones our windows are in
5392
0
    for (ImGuiViewportP* viewport : g.Viewports)
5393
0
    {
5394
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5395
0
            continue;
5396
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5397
0
            continue;
5398
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5399
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5400
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5401
0
    }
5402
0
}
5403
5404
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5405
void ImGui::EndFrame()
5406
161k
{
5407
161k
    ImGuiContext& g = *GImGui;
5408
161k
    IM_ASSERT(g.Initialized);
5409
5410
    // Don't process EndFrame() multiple times.
5411
161k
    if (g.FrameCountEnded == g.FrameCount)
5412
80.5k
        return;
5413
80.5k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5414
5415
80.5k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5416
5417
80.5k
    ErrorCheckEndFrameSanityChecks();
5418
5419
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5420
80.5k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5421
80.5k
    if (g.IO.PlatformSetImeDataFn != NULL && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5422
0
    {
5423
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5424
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.PlatformSetImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5425
0
        if (viewport == NULL)
5426
0
            viewport = GetMainViewport();
5427
0
        g.IO.PlatformSetImeDataFn(&g, viewport, ime_data);
5428
0
    }
5429
5430
    // Hide implicit/fallback "Debug" window if it hasn't been used
5431
80.5k
    g.WithinFrameScopeWithImplicitWindow = false;
5432
80.5k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5433
80.5k
        g.CurrentWindow->Active = false;
5434
80.5k
    End();
5435
5436
    // Update navigation: CTRL+Tab, wrap-around requests
5437
80.5k
    NavEndFrame();
5438
5439
    // Update docking
5440
80.5k
    DockContextEndFrame(&g);
5441
5442
80.5k
    SetCurrentViewport(NULL, NULL);
5443
5444
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5445
80.5k
    if (g.DragDropActive)
5446
3.50k
    {
5447
3.50k
        bool is_delivered = g.DragDropPayload.Delivery;
5448
3.50k
        bool is_elapsed = (g.DragDropSourceFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_PayloadAutoExpire) || g.DragDropMouseButton == -1 || !IsMouseDown(g.DragDropMouseButton));
5449
3.50k
        if (is_delivered || is_elapsed)
5450
9
            ClearDragDrop();
5451
3.50k
    }
5452
5453
    // Drag and Drop: Fallback for missing source tooltip. This is not ideal but better than nothing.
5454
    // If you want to handle source item disappearing: instead of submitting your description tooltip
5455
    // in the BeginDragDropSource() block of the dragged item, you can submit them from a safe single spot
5456
    // (e.g. end of your item loop, or before EndFrame) by reading payload data.
5457
    // In the typical case, the contents of drag tooltip should be possible to infer solely from payload data.
5458
80.5k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5459
0
    {
5460
0
        g.DragDropWithinSource = true;
5461
0
        SetTooltip("...");
5462
0
        g.DragDropWithinSource = false;
5463
0
    }
5464
5465
    // End frame
5466
80.5k
    g.WithinFrameScope = false;
5467
80.5k
    g.FrameCountEnded = g.FrameCount;
5468
5469
    // Initiate moving window + handle left-click and right-click focus
5470
80.5k
    UpdateMouseMovingWindowEndFrame();
5471
5472
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5473
80.5k
    UpdateViewportsEndFrame();
5474
5475
    // Sort the window list so that all child windows are after their parent
5476
    // We cannot do that on FocusWindow() because children may not exist yet
5477
80.5k
    g.WindowsTempSortBuffer.resize(0);
5478
80.5k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5479
80.5k
    for (ImGuiWindow* window : g.Windows)
5480
292k
    {
5481
292k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5482
25.3k
            continue;
5483
267k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5484
267k
    }
5485
5486
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5487
80.5k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5488
80.5k
    g.Windows.swap(g.WindowsTempSortBuffer);
5489
80.5k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5490
5491
    // Unlock font atlas
5492
80.5k
    g.IO.Fonts->Locked = false;
5493
5494
    // Clear Input data for next frame
5495
80.5k
    g.IO.MousePosPrev = g.IO.MousePos;
5496
80.5k
    g.IO.AppFocusLost = false;
5497
80.5k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5498
80.5k
    g.IO.InputQueueCharacters.resize(0);
5499
5500
80.5k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5501
80.5k
}
5502
5503
// Prepare the data for rendering so you can call GetDrawData()
5504
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5505
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5506
void ImGui::Render()
5507
80.5k
{
5508
80.5k
    ImGuiContext& g = *GImGui;
5509
80.5k
    IM_ASSERT(g.Initialized);
5510
5511
80.5k
    if (g.FrameCountEnded != g.FrameCount)
5512
80.5k
        EndFrame();
5513
80.5k
    if (g.FrameCountRendered == g.FrameCount)
5514
0
        return;
5515
80.5k
    g.FrameCountRendered = g.FrameCount;
5516
5517
80.5k
    g.IO.MetricsRenderWindows = 0;
5518
80.5k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5519
5520
    // Add background ImDrawList (for each active viewport)
5521
80.5k
    for (ImGuiViewportP* viewport : g.Viewports)
5522
80.5k
    {
5523
80.5k
        InitViewportDrawData(viewport);
5524
80.5k
        if (viewport->BgFgDrawLists[0] != NULL)
5525
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5526
80.5k
    }
5527
5528
    // Draw modal/window whitening backgrounds
5529
80.5k
    RenderDimmedBackgrounds();
5530
5531
    // Add ImDrawList to render
5532
80.5k
    ImGuiWindow* windows_to_render_top_most[2];
5533
80.5k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5534
80.5k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5535
80.5k
    for (ImGuiWindow* window : g.Windows)
5536
292k
    {
5537
292k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5538
292k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5539
80.5k
            AddRootWindowToDrawData(window);
5540
292k
    }
5541
241k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5542
161k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5543
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5544
5545
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5546
80.5k
    if (g.IO.MouseDrawCursor && g.MouseCursor != ImGuiMouseCursor_None)
5547
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5548
5549
    // Setup ImDrawData structures for end-user
5550
80.5k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5551
80.5k
    for (ImGuiViewportP* viewport : g.Viewports)
5552
80.5k
    {
5553
80.5k
        FlattenDrawDataIntoSingleLayer(&viewport->DrawDataBuilder);
5554
5555
        // Add foreground ImDrawList (for each active viewport)
5556
80.5k
        if (viewport->BgFgDrawLists[1] != NULL)
5557
0
            AddDrawListToDrawDataEx(&viewport->DrawDataP, viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5558
5559
        // We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch).
5560
80.5k
        ImDrawData* draw_data = &viewport->DrawDataP;
5561
80.5k
        IM_ASSERT(draw_data->CmdLists.Size == draw_data->CmdListsCount);
5562
80.5k
        for (ImDrawList* draw_list : draw_data->CmdLists)
5563
105k
            draw_list->_PopUnusedDrawCmd();
5564
5565
80.5k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5566
80.5k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5567
80.5k
    }
5568
5569
80.5k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5570
80.5k
}
5571
5572
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5573
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5574
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5575
161k
{
5576
161k
    ImGuiContext& g = *GImGui;
5577
5578
161k
    const char* text_display_end;
5579
161k
    if (hide_text_after_double_hash)
5580
161k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5581
6
    else
5582
6
        text_display_end = text_end;
5583
5584
161k
    ImFont* font = g.Font;
5585
161k
    const float font_size = g.FontSize;
5586
161k
    if (text == text_display_end)
5587
0
        return ImVec2(0.0f, font_size);
5588
161k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5589
5590
    // Round
5591
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5592
    // FIXME: Investigate using ceilf or e.g.
5593
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5594
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5595
161k
    text_size.x = IM_TRUNC(text_size.x + 0.99999f);
5596
5597
161k
    return text_size;
5598
161k
}
5599
5600
// Find window given position, search front-to-back
5601
// - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow.
5602
// - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5603
//   with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5604
//   called, aka before the next Begin(). Moving window isn't affected.
5605
// - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here.
5606
void ImGui::FindHoveredWindowEx(const ImVec2& pos, bool find_first_and_in_any_viewport, ImGuiWindow** out_hovered_window, ImGuiWindow** out_hovered_window_under_moving_window)
5607
80.5k
{
5608
80.5k
    ImGuiContext& g = *GImGui;
5609
80.5k
    ImGuiWindow* hovered_window = NULL;
5610
80.5k
    ImGuiWindow* hovered_window_under_moving_window = NULL;
5611
5612
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5613
80.5k
    ImGuiViewportP* backup_moving_window_viewport = NULL;
5614
80.5k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5615
5.13k
    {
5616
5.13k
        backup_moving_window_viewport = g.MovingWindow->Viewport;
5617
5.13k
        g.MovingWindow->Viewport = g.MouseViewport;
5618
5.13k
        if (!(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5619
5.13k
            hovered_window = g.MovingWindow;
5620
5.13k
    }
5621
5622
80.5k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5623
80.5k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5624
342k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5625
274k
    {
5626
274k
        ImGuiWindow* window = g.Windows[i];
5627
274k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5628
274k
        if (!window->Active || window->Hidden)
5629
168k
            continue;
5630
105k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5631
0
            continue;
5632
105k
        IM_ASSERT(window->Viewport);
5633
105k
        if (window->Viewport != g.MouseViewport)
5634
0
            continue;
5635
5636
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5637
105k
        ImVec2 hit_padding = (window->Flags & (ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) ? padding_regular : padding_for_resize;
5638
105k
        if (!window->OuterRectClipped.ContainsWithPad(pos, hit_padding))
5639
87.9k
            continue;
5640
5641
        // Support for one rectangular hole in any given window
5642
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5643
17.5k
        if (window->HitTestHoleSize.x != 0)
5644
0
        {
5645
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5646
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5647
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(pos))
5648
0
                continue;
5649
0
        }
5650
5651
17.5k
        if (find_first_and_in_any_viewport)
5652
0
        {
5653
0
            hovered_window = window;
5654
0
            break;
5655
0
        }
5656
17.5k
        else
5657
17.5k
        {
5658
17.5k
            if (hovered_window == NULL)
5659
12.5k
                hovered_window = window;
5660
17.5k
            IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5661
17.5k
            if (hovered_window_under_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5662
12.5k
                hovered_window_under_moving_window = window;
5663
17.5k
            if (hovered_window && hovered_window_under_moving_window)
5664
12.5k
                break;
5665
17.5k
        }
5666
17.5k
    }
5667
5668
80.5k
    *out_hovered_window = hovered_window;
5669
80.5k
    if (out_hovered_window_under_moving_window != NULL)
5670
80.5k
        *out_hovered_window_under_moving_window = hovered_window_under_moving_window;
5671
80.5k
    if (find_first_and_in_any_viewport == false && g.MovingWindow)
5672
5.13k
        g.MovingWindow->Viewport = backup_moving_window_viewport;
5673
80.5k
}
5674
5675
bool ImGui::IsItemActive()
5676
160k
{
5677
160k
    ImGuiContext& g = *GImGui;
5678
160k
    if (g.ActiveId)
5679
10.0k
        return g.ActiveId == g.LastItemData.ID;
5680
150k
    return false;
5681
160k
}
5682
5683
bool ImGui::IsItemActivated()
5684
0
{
5685
0
    ImGuiContext& g = *GImGui;
5686
0
    if (g.ActiveId)
5687
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5688
0
            return true;
5689
0
    return false;
5690
0
}
5691
5692
bool ImGui::IsItemDeactivated()
5693
0
{
5694
0
    ImGuiContext& g = *GImGui;
5695
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5696
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5697
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5698
0
}
5699
5700
bool ImGui::IsItemDeactivatedAfterEdit()
5701
0
{
5702
0
    ImGuiContext& g = *GImGui;
5703
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5704
0
}
5705
5706
// == GetItemID() == GetFocusID()
5707
bool ImGui::IsItemFocused()
5708
0
{
5709
0
    ImGuiContext& g = *GImGui;
5710
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5711
0
        return false;
5712
5713
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5714
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5715
0
    ImGuiWindow* window = g.CurrentWindow;
5716
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5717
0
        return false;
5718
5719
0
    return true;
5720
0
}
5721
5722
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5723
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5724
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5725
0
{
5726
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5727
0
}
5728
5729
bool ImGui::IsItemToggledOpen()
5730
0
{
5731
0
    ImGuiContext& g = *GImGui;
5732
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5733
0
}
5734
5735
// Call after a Selectable() or TreeNode() involved in multi-selection.
5736
// Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose.
5737
// This is only meant to be called inside a BeginMultiSelect()/EndMultiSelect() block.
5738
// (Outside of multi-select, it would be misleading/ambiguous to report this signal, as widgets
5739
// return e.g. a pressed event and user code is in charge of altering selection in ways we cannot predict.)
5740
bool ImGui::IsItemToggledSelection()
5741
0
{
5742
0
    ImGuiContext& g = *GImGui;
5743
0
    IM_ASSERT(g.CurrentMultiSelect != NULL); // Can only be used inside a BeginMultiSelect()/EndMultiSelect()
5744
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5745
0
}
5746
5747
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
5748
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
5749
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
5750
bool ImGui::IsAnyItemHovered()
5751
0
{
5752
0
    ImGuiContext& g = *GImGui;
5753
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5754
0
}
5755
5756
bool ImGui::IsAnyItemActive()
5757
0
{
5758
0
    ImGuiContext& g = *GImGui;
5759
0
    return g.ActiveId != 0;
5760
0
}
5761
5762
bool ImGui::IsAnyItemFocused()
5763
0
{
5764
0
    ImGuiContext& g = *GImGui;
5765
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5766
0
}
5767
5768
bool ImGui::IsItemVisible()
5769
0
{
5770
0
    ImGuiContext& g = *GImGui;
5771
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5772
0
}
5773
5774
bool ImGui::IsItemEdited()
5775
0
{
5776
0
    ImGuiContext& g = *GImGui;
5777
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5778
0
}
5779
5780
// Allow next item to be overlapped by subsequent items.
5781
// This works by requiring HoveredId to match for two subsequent frames,
5782
// so if a following items overwrite it our interactions will naturally be disabled.
5783
void ImGui::SetNextItemAllowOverlap()
5784
0
{
5785
0
    ImGuiContext& g = *GImGui;
5786
0
    g.NextItemData.ItemFlags |= ImGuiItemFlags_AllowOverlap;
5787
0
}
5788
5789
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5790
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5791
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5792
void ImGui::SetItemAllowOverlap()
5793
{
5794
    ImGuiContext& g = *GImGui;
5795
    ImGuiID id = g.LastItemData.ID;
5796
    if (g.HoveredId == id)
5797
        g.HoveredIdAllowOverlap = true;
5798
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5799
        g.ActiveIdAllowOverlap = true;
5800
}
5801
#endif
5802
5803
// This is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations.
5804
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version if needed?
5805
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5806
4.89k
{
5807
4.89k
    ImGuiContext& g = *GImGui;
5808
4.89k
    IM_ASSERT(g.ActiveId != 0);
5809
4.89k
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5810
4.89k
    g.ActiveIdUsingAllKeyboardKeys = true;
5811
4.89k
    NavMoveRequestCancel();
5812
4.89k
}
5813
5814
ImGuiID ImGui::GetItemID()
5815
0
{
5816
0
    ImGuiContext& g = *GImGui;
5817
0
    return g.LastItemData.ID;
5818
0
}
5819
5820
ImVec2 ImGui::GetItemRectMin()
5821
0
{
5822
0
    ImGuiContext& g = *GImGui;
5823
0
    return g.LastItemData.Rect.Min;
5824
0
}
5825
5826
ImVec2 ImGui::GetItemRectMax()
5827
0
{
5828
0
    ImGuiContext& g = *GImGui;
5829
0
    return g.LastItemData.Rect.Max;
5830
0
}
5831
5832
ImVec2 ImGui::GetItemRectSize()
5833
0
{
5834
0
    ImGuiContext& g = *GImGui;
5835
0
    return g.LastItemData.Rect.GetSize();
5836
0
}
5837
5838
// Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'.
5839
// ImGuiChildFlags_Border is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details!
5840
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5841
25.3k
{
5842
25.3k
    ImGuiID id = GetCurrentWindow()->GetID(str_id);
5843
25.3k
    return BeginChildEx(str_id, id, size_arg, child_flags, window_flags);
5844
25.3k
}
5845
5846
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5847
0
{
5848
0
    return BeginChildEx(NULL, id, size_arg, child_flags, window_flags);
5849
0
}
5850
5851
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, ImGuiChildFlags child_flags, ImGuiWindowFlags window_flags)
5852
25.3k
{
5853
25.3k
    ImGuiContext& g = *GImGui;
5854
25.3k
    ImGuiWindow* parent_window = g.CurrentWindow;
5855
25.3k
    IM_ASSERT(id != 0);
5856
5857
    // Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument.
5858
25.3k
    const ImGuiChildFlags ImGuiChildFlags_SupportedMask_ = ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding | ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize | ImGuiChildFlags_FrameStyle | ImGuiChildFlags_NavFlattened;
5859
25.3k
    IM_UNUSED(ImGuiChildFlags_SupportedMask_);
5860
25.3k
    IM_ASSERT((child_flags & ~ImGuiChildFlags_SupportedMask_) == 0 && "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?");
5861
25.3k
    IM_ASSERT((window_flags & ImGuiWindowFlags_AlwaysAutoResize) == 0 && "Cannot specify ImGuiWindowFlags_AlwaysAutoResize for BeginChild(). Use ImGuiChildFlags_AlwaysAutoResize!");
5862
25.3k
    if (child_flags & ImGuiChildFlags_AlwaysAutoResize)
5863
0
    {
5864
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0 && "Cannot use ImGuiChildFlags_ResizeX or ImGuiChildFlags_ResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5865
0
        IM_ASSERT((child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY)) != 0 && "Must use ImGuiChildFlags_AutoResizeX or ImGuiChildFlags_AutoResizeY with ImGuiChildFlags_AlwaysAutoResize!");
5866
0
    }
5867
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5868
    if (window_flags & ImGuiWindowFlags_AlwaysUseWindowPadding)
5869
        child_flags |= ImGuiChildFlags_AlwaysUseWindowPadding;
5870
    if (window_flags & ImGuiWindowFlags_NavFlattened)
5871
        child_flags |= ImGuiChildFlags_NavFlattened;
5872
#endif
5873
25.3k
    if (child_flags & ImGuiChildFlags_AutoResizeX)
5874
0
        child_flags &= ~ImGuiChildFlags_ResizeX;
5875
25.3k
    if (child_flags & ImGuiChildFlags_AutoResizeY)
5876
0
        child_flags &= ~ImGuiChildFlags_ResizeY;
5877
5878
    // Set window flags
5879
25.3k
    window_flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking;
5880
25.3k
    window_flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
5881
25.3k
    if (child_flags & (ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY | ImGuiChildFlags_AlwaysAutoResize))
5882
0
        window_flags |= ImGuiWindowFlags_AlwaysAutoResize;
5883
25.3k
    if ((child_flags & (ImGuiChildFlags_ResizeX | ImGuiChildFlags_ResizeY)) == 0)
5884
25.3k
        window_flags |= ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
5885
5886
    // Special framed style
5887
25.3k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5888
0
    {
5889
0
        PushStyleColor(ImGuiCol_ChildBg, g.Style.Colors[ImGuiCol_FrameBg]);
5890
0
        PushStyleVar(ImGuiStyleVar_ChildRounding, g.Style.FrameRounding);
5891
0
        PushStyleVar(ImGuiStyleVar_ChildBorderSize, g.Style.FrameBorderSize);
5892
0
        PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.FramePadding);
5893
0
        child_flags |= ImGuiChildFlags_Border | ImGuiChildFlags_AlwaysUseWindowPadding;
5894
0
        window_flags |= ImGuiWindowFlags_NoMove;
5895
0
    }
5896
5897
    // Forward child flags
5898
25.3k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasChildFlags;
5899
25.3k
    g.NextWindowData.ChildFlags = child_flags;
5900
5901
    // Forward size
5902
    // Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags_ResizeXXX is set.
5903
    // (the alternative would to store conditional flags per axis, which is possible but more code)
5904
25.3k
    const ImVec2 size_avail = GetContentRegionAvail();
5905
25.3k
    const ImVec2 size_default((child_flags & ImGuiChildFlags_AutoResizeX) ? 0.0f : size_avail.x, (child_flags & ImGuiChildFlags_AutoResizeY) ? 0.0f : size_avail.y);
5906
25.3k
    const ImVec2 size = CalcItemSize(size_arg, size_default.x, size_default.y);
5907
25.3k
    SetNextWindowSize(size);
5908
5909
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5910
    // FIXME: 2023/11/14: commented out shorted version. We had an issue with multiple ### in child window path names, which the trailing hash helped workaround.
5911
    // e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it.
5912
25.3k
    const char* temp_window_name;
5913
    /*if (name && parent_window->IDStack.back() == parent_window->ID)
5914
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s", parent_window->Name, name); // May omit ID if in root of ID stack
5915
    else*/
5916
25.3k
    if (name)
5917
25.3k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5918
0
    else
5919
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5920
5921
    // Set style
5922
25.3k
    const float backup_border_size = g.Style.ChildBorderSize;
5923
25.3k
    if ((child_flags & ImGuiChildFlags_Border) == 0)
5924
16.3k
        g.Style.ChildBorderSize = 0.0f;
5925
5926
    // Begin into window
5927
25.3k
    const bool ret = Begin(temp_window_name, NULL, window_flags);
5928
5929
    // Restore style
5930
25.3k
    g.Style.ChildBorderSize = backup_border_size;
5931
25.3k
    if (child_flags & ImGuiChildFlags_FrameStyle)
5932
0
    {
5933
0
        PopStyleVar(3);
5934
0
        PopStyleColor();
5935
0
    }
5936
5937
25.3k
    ImGuiWindow* child_window = g.CurrentWindow;
5938
25.3k
    child_window->ChildId = id;
5939
5940
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5941
    // While this is not really documented/defined, it seems that the expected thing to do.
5942
25.3k
    if (child_window->BeginCount == 1)
5943
25.3k
        parent_window->DC.CursorPos = child_window->Pos;
5944
5945
    // Process navigation-in immediately so NavInit can run on first frame
5946
    // Can enter a child if (A) it has navigable items or (B) it can be scrolled.
5947
25.3k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5948
25.3k
    if (g.ActiveId == temp_id_for_activation)
5949
0
        ClearActiveID();
5950
25.3k
    if (g.NavActivateId == id && !(child_flags & ImGuiChildFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5951
0
    {
5952
0
        FocusWindow(child_window);
5953
0
        NavInitWindow(child_window, false);
5954
0
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5955
0
        g.ActiveIdSource = g.NavInputSource;
5956
0
    }
5957
25.3k
    return ret;
5958
25.3k
}
5959
5960
void ImGui::EndChild()
5961
25.3k
{
5962
25.3k
    ImGuiContext& g = *GImGui;
5963
25.3k
    ImGuiWindow* child_window = g.CurrentWindow;
5964
5965
25.3k
    IM_ASSERT(g.WithinEndChild == false);
5966
25.3k
    IM_ASSERT(child_window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5967
5968
25.3k
    g.WithinEndChild = true;
5969
25.3k
    ImVec2 child_size = child_window->Size;
5970
25.3k
    End();
5971
25.3k
    if (child_window->BeginCount == 1)
5972
25.3k
    {
5973
25.3k
        ImGuiWindow* parent_window = g.CurrentWindow;
5974
25.3k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + child_size);
5975
25.3k
        ItemSize(child_size);
5976
25.3k
        const bool nav_flattened = (child_window->ChildFlags & ImGuiChildFlags_NavFlattened) != 0;
5977
25.3k
        if ((child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY) && !nav_flattened)
5978
21.3k
        {
5979
21.3k
            ItemAdd(bb, child_window->ChildId);
5980
21.3k
            RenderNavHighlight(bb, child_window->ChildId);
5981
5982
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5983
21.3k
            if (child_window->DC.NavLayersActiveMask == 0 && child_window == g.NavWindow)
5984
13.1k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_Compact);
5985
21.3k
        }
5986
3.95k
        else
5987
3.95k
        {
5988
            // Not navigable into
5989
            // - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs.
5990
            // - We could later decide to not apply this path if ImGuiChildFlags_FrameStyle or ImGuiChildFlags_Borders is set.
5991
3.95k
            ItemAdd(bb, child_window->ChildId, NULL, ImGuiItemFlags_NoNav);
5992
5993
            // But when flattened we directly reach items, adjust active layer mask accordingly
5994
3.95k
            if (nav_flattened)
5995
0
                parent_window->DC.NavLayersActiveMaskNext |= child_window->DC.NavLayersActiveMaskNext;
5996
3.95k
        }
5997
25.3k
        if (g.HoveredWindow == child_window)
5998
73
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5999
25.3k
    }
6000
25.3k
    g.WithinEndChild = false;
6001
25.3k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
6002
25.3k
}
6003
6004
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
6005
28
{
6006
28
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
6007
28
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
6008
28
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
6009
28
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
6010
28
}
6011
6012
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
6013
186k
{
6014
186k
    ImGuiContext& g = *GImGui;
6015
186k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
6016
186k
}
6017
6018
ImGuiWindow* ImGui::FindWindowByName(const char* name)
6019
186k
{
6020
186k
    ImGuiID id = ImHashStr(name);
6021
186k
    return FindWindowByID(id);
6022
186k
}
6023
6024
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6025
0
{
6026
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6027
0
    window->ViewportPos = main_viewport->Pos;
6028
0
    if (settings->ViewportId)
6029
0
    {
6030
0
        window->ViewportId = settings->ViewportId;
6031
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
6032
0
    }
6033
0
    window->Pos = ImTrunc(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
6034
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
6035
0
        window->Size = window->SizeFull = ImTrunc(ImVec2(settings->Size.x, settings->Size.y));
6036
0
    window->Collapsed = settings->Collapsed;
6037
0
    window->DockId = settings->DockId;
6038
0
    window->DockOrder = settings->DockOrder;
6039
0
}
6040
6041
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
6042
186k
{
6043
186k
    ImGuiContext& g = *GImGui;
6044
6045
186k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
6046
186k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
6047
186k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
6048
3
    {
6049
3
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
6050
3
        g.WindowsFocusOrder.push_back(window);
6051
3
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
6052
3
    }
6053
186k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
6054
0
    {
6055
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
6056
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
6057
0
            g.WindowsFocusOrder[n]->FocusOrder--;
6058
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
6059
0
        window->FocusOrder = -1;
6060
0
    }
6061
186k
    window->IsExplicitChild = new_is_explicit_child;
6062
186k
}
6063
6064
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
6065
4
{
6066
    // Initial window state with e.g. default/arbitrary window position
6067
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
6068
4
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
6069
4
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
6070
4
    window->Size = window->SizeFull = ImVec2(0, 0);
6071
4
    window->ViewportPos = main_viewport->Pos;
6072
4
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
6073
6074
4
    if (settings != NULL)
6075
0
    {
6076
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
6077
0
        ApplyWindowSettings(window, settings);
6078
0
    }
6079
4
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
6080
6081
4
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
6082
1
    {
6083
1
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
6084
1
        window->AutoFitOnlyGrows = false;
6085
1
    }
6086
3
    else
6087
3
    {
6088
3
        if (window->Size.x <= 0.0f)
6089
3
            window->AutoFitFramesX = 2;
6090
3
        if (window->Size.y <= 0.0f)
6091
3
            window->AutoFitFramesY = 2;
6092
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
6093
3
    }
6094
4
}
6095
6096
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
6097
4
{
6098
    // Create window the first time
6099
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
6100
4
    ImGuiContext& g = *GImGui;
6101
4
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
6102
4
    window->Flags = flags;
6103
4
    g.WindowsById.SetVoidPtr(window->ID, window);
6104
6105
4
    ImGuiWindowSettings* settings = NULL;
6106
4
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
6107
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
6108
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
6109
6110
4
    InitOrLoadWindowSettings(window, settings);
6111
6112
4
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
6113
0
        g.Windows.push_front(window); // Quite slow but rare and only once
6114
4
    else
6115
4
        g.Windows.push_back(window);
6116
6117
4
    return window;
6118
4
}
6119
6120
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
6121
0
{
6122
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
6123
0
}
6124
6125
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
6126
559k
{
6127
559k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
6128
559k
}
6129
6130
static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window)
6131
559k
{
6132
    // We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
6133
    // FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller.
6134
    // Perhaps should tend further a neater test for this.
6135
559k
    ImGuiContext& g = *GImGui;
6136
559k
    ImVec2 size_min;
6137
559k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Popup))
6138
76.0k
    {
6139
76.0k
        size_min.x = (window->ChildFlags & ImGuiChildFlags_ResizeX) ? g.Style.WindowMinSize.x : 4.0f;
6140
76.0k
        size_min.y = (window->ChildFlags & ImGuiChildFlags_ResizeY) ? g.Style.WindowMinSize.y : 4.0f;
6141
76.0k
    }
6142
483k
    else
6143
483k
    {
6144
483k
        size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f;
6145
483k
        size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f;
6146
483k
    }
6147
6148
    // Reduce artifacts with very small windows
6149
559k
    ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
6150
559k
    size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight + window_for_height->MenuBarHeight + ImMax(0.0f, g.Style.WindowRounding - 1.0f));
6151
559k
    return size_min;
6152
559k
}
6153
6154
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
6155
373k
{
6156
373k
    ImGuiContext& g = *GImGui;
6157
373k
    ImVec2 new_size = size_desired;
6158
373k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
6159
0
    {
6160
        // See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max.
6161
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
6162
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
6163
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
6164
0
        if (g.NextWindowData.SizeCallback)
6165
0
        {
6166
0
            ImGuiSizeCallbackData data;
6167
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
6168
0
            data.Pos = window->Pos;
6169
0
            data.CurrentSize = window->SizeFull;
6170
0
            data.DesiredSize = new_size;
6171
0
            g.NextWindowData.SizeCallback(&data);
6172
0
            new_size = data.DesiredSize;
6173
0
        }
6174
0
        new_size.x = IM_TRUNC(new_size.x);
6175
0
        new_size.y = IM_TRUNC(new_size.y);
6176
0
    }
6177
6178
    // Minimum size
6179
373k
    ImVec2 size_min = CalcWindowMinSize(window);
6180
373k
    return ImMax(new_size, size_min);
6181
373k
}
6182
6183
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
6184
186k
{
6185
186k
    bool preserve_old_content_sizes = false;
6186
186k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
6187
55.2k
        preserve_old_content_sizes = true;
6188
131k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
6189
301
        preserve_old_content_sizes = true;
6190
186k
    if (preserve_old_content_sizes)
6191
55.5k
    {
6192
55.5k
        *content_size_current = window->ContentSize;
6193
55.5k
        *content_size_ideal = window->ContentSizeIdeal;
6194
55.5k
        return;
6195
55.5k
    }
6196
6197
130k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
6198
130k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
6199
130k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_TRUNC(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
6200
130k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_TRUNC(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
6201
130k
}
6202
6203
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
6204
186k
{
6205
186k
    ImGuiContext& g = *GImGui;
6206
186k
    ImGuiStyle& style = g.Style;
6207
186k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
6208
186k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
6209
186k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
6210
186k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
6211
186k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
6212
3
    {
6213
        // Tooltip always resize
6214
3
        return size_desired;
6215
3
    }
6216
186k
    else
6217
186k
    {
6218
        // Maximum window size is determined by the viewport size or monitor size
6219
186k
        ImVec2 size_min = CalcWindowMinSize(window);
6220
186k
        ImVec2 size_max = ImVec2(FLT_MAX, FLT_MAX);
6221
6222
        // Child windows are layed within their parent (unless they are also popups/menus) and thus have no restriction
6223
186k
        if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || (window->Flags & ImGuiWindowFlags_Popup) != 0)
6224
161k
        {
6225
161k
            if (!window->ViewportOwned)
6226
161k
                size_max = ImGui::GetMainViewport()->WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6227
161k
            const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
6228
161k
            if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
6229
0
                size_max = g.PlatformIO.Monitors[monitor_idx].WorkSize - style.DisplaySafeAreaPadding * 2.0f;
6230
161k
        }
6231
6232
186k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, size_max));
6233
6234
        // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one axis may be auto-fit when calculating scrollbars,
6235
        // we may need to compute/store three variants of size_auto_fit, for x/y/xy.
6236
        // Here we implement a workaround for child windows only, but a full solution would apply to normal windows as well:
6237
186k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && !(window->ChildFlags & ImGuiChildFlags_ResizeY))
6238
0
            size_auto_fit.y = window->SizeFull.y;
6239
186k
        else if (!(window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->ChildFlags & ImGuiChildFlags_ResizeY))
6240
0
            size_auto_fit.x = window->SizeFull.x;
6241
6242
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
6243
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
6244
186k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6245
186k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
6246
186k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
6247
186k
        if (will_have_scrollbar_x)
6248
25.3k
            size_auto_fit.y += style.ScrollbarSize;
6249
186k
        if (will_have_scrollbar_y)
6250
331
            size_auto_fit.x += style.ScrollbarSize;
6251
186k
        return size_auto_fit;
6252
186k
    }
6253
186k
}
6254
6255
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6256
0
{
6257
0
    ImVec2 size_contents_current;
6258
0
    ImVec2 size_contents_ideal;
6259
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6260
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6261
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6262
0
    return size_final;
6263
0
}
6264
6265
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6266
131k
{
6267
131k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6268
3
        return ImGuiCol_PopupBg;
6269
131k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6270
25.3k
        return ImGuiCol_ChildBg;
6271
105k
    return ImGuiCol_WindowBg;
6272
131k
}
6273
6274
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6275
174
{
6276
174
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6277
174
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6278
174
    ImVec2 size_expected = pos_max - pos_min;
6279
174
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6280
174
    *out_pos = pos_min;
6281
174
    if (corner_norm.x == 0.0f)
6282
174
        out_pos->x -= (size_constrained.x - size_expected.x);
6283
174
    if (corner_norm.y == 0.0f)
6284
174
        out_pos->y -= (size_constrained.y - size_expected.y);
6285
174
    *out_size = size_constrained;
6286
174
}
6287
6288
// Data for resizing from resize grip / corner
6289
struct ImGuiResizeGripDef
6290
{
6291
    ImVec2  CornerPosN;
6292
    ImVec2  InnerDir;
6293
    int     AngleMin12, AngleMax12;
6294
};
6295
static const ImGuiResizeGripDef resize_grip_def[4] =
6296
{
6297
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6298
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6299
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6300
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6301
};
6302
6303
// Data for resizing from borders
6304
struct ImGuiResizeBorderDef
6305
{
6306
    ImVec2  InnerDir;               // Normal toward inside
6307
    ImVec2  SegmentN1, SegmentN2;   // End positions, normalized (0,0: upper left)
6308
    float   OuterAngle;             // Angle toward outside
6309
};
6310
static const ImGuiResizeBorderDef resize_border_def[4] =
6311
{
6312
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6313
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6314
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6315
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6316
};
6317
6318
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6319
102k
{
6320
102k
    ImRect rect = window->Rect();
6321
102k
    if (thickness == 0.0f)
6322
1.15k
        rect.Max -= ImVec2(1, 1);
6323
102k
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6324
77.3k
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6325
52.0k
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6326
25.3k
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6327
0
    IM_ASSERT(0);
6328
0
    return ImRect();
6329
25.3k
}
6330
6331
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6332
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6333
0
{
6334
0
    IM_ASSERT(n >= 0 && n < 4);
6335
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6336
0
    id = ImHashStr("#RESIZE", 0, id);
6337
0
    id = ImHashData(&n, sizeof(int), id);
6338
0
    return id;
6339
0
}
6340
6341
// Borders (Left, Right, Up, Down)
6342
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6343
0
{
6344
0
    IM_ASSERT(dir >= 0 && dir < 4);
6345
0
    int n = (int)dir + 4;
6346
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6347
0
    id = ImHashStr("#RESIZE", 0, id);
6348
0
    id = ImHashData(&n, sizeof(int), id);
6349
0
    return id;
6350
0
}
6351
6352
// Handle resize for: Resize Grips, Borders, Gamepad
6353
// Return true when using auto-fit (double-click on resize grip)
6354
static int ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_hovered, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6355
131k
{
6356
131k
    ImGuiContext& g = *GImGui;
6357
131k
    ImGuiWindowFlags flags = window->Flags;
6358
6359
131k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6360
25.3k
        return false;
6361
105k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6362
80.5k
        return false;
6363
6364
25.3k
    int ret_auto_fit_mask = 0x00;
6365
25.3k
    const float grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6366
25.3k
    const float grip_hover_inner_size = (resize_grip_count > 0) ? IM_TRUNC(grip_draw_size * 0.75f) : 0.0f;
6367
25.3k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6368
6369
25.3k
    ImRect clamp_rect = visibility_rect;
6370
25.3k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6371
25.3k
    if (window_move_from_title_bar)
6372
0
        clamp_rect.Min.y -= window->TitleBarHeight;
6373
6374
25.3k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6375
25.3k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6376
6377
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6378
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6379
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6380
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6381
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6382
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6383
25.3k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6384
25.3k
    if (clip_with_viewport_rect)
6385
25.3k
        window->ClipRect = window->Viewport->GetMainRect();
6386
6387
    // Resize grips and borders are on layer 1
6388
25.3k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6389
6390
    // Manual resize grips
6391
25.3k
    PushID("#RESIZE");
6392
76.0k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6393
50.6k
    {
6394
50.6k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6395
50.6k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6396
6397
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6398
50.6k
        bool hovered, held;
6399
50.6k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6400
50.6k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6401
50.6k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6402
50.6k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6403
50.6k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6404
50.6k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6405
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6406
50.6k
        if (hovered || held)
6407
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6408
6409
50.6k
        if (held && g.IO.MouseDoubleClicked[0])
6410
0
        {
6411
            // Auto-fit when double-clicking
6412
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6413
0
            ret_auto_fit_mask = 0x03; // Both axises
6414
0
            ClearActiveID();
6415
0
        }
6416
50.6k
        else if (held)
6417
0
        {
6418
            // Resize from any of the four corners
6419
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6420
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6421
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6422
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6423
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6424
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6425
0
        }
6426
6427
        // Only lower-left grip is visible before hovering/activating
6428
50.6k
        if (resize_grip_n == 0 || held || hovered)
6429
25.3k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6430
50.6k
    }
6431
6432
25.3k
    int resize_border_mask = 0x00;
6433
25.3k
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
6434
0
        resize_border_mask |= ((window->ChildFlags & ImGuiChildFlags_ResizeX) ? 0x02 : 0) | ((window->ChildFlags & ImGuiChildFlags_ResizeY) ? 0x08 : 0);
6435
25.3k
    else
6436
25.3k
        resize_border_mask = g.IO.ConfigWindowsResizeFromEdges ? 0x0F : 0x00;
6437
126k
    for (int border_n = 0; border_n < 4; border_n++)
6438
101k
    {
6439
101k
        if ((resize_border_mask & (1 << border_n)) == 0)
6440
0
            continue;
6441
101k
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6442
101k
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6443
6444
101k
        bool hovered, held;
6445
101k
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6446
101k
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6447
101k
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6448
101k
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6449
        //GetForegroundDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6450
101k
        if (hovered && g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER)
6451
53
            hovered = false;
6452
101k
        if (hovered || held)
6453
1.15k
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6454
101k
        if (held && g.IO.MouseDoubleClicked[0])
6455
13
        {
6456
            // Double-clicking bottom or right border auto-fit on this axis
6457
            // FIXME: CalcWindowAutoFitSize() doesn't take into account that only one side may be auto-fit when calculating scrollbars.
6458
            // FIXME: Support top and right borders: rework CalcResizePosSizeFromAnyCorner() to be reusable in both cases.
6459
13
            if (border_n == 1 || border_n == 3) // Right and bottom border
6460
0
            {
6461
0
                size_target[axis] = CalcWindowSizeAfterConstraint(window, size_auto_fit)[axis];
6462
0
                ret_auto_fit_mask |= (1 << axis);
6463
0
                hovered = held = false; // So border doesn't show highlighted at new position
6464
0
            }
6465
13
            ClearActiveID();
6466
13
        }
6467
101k
        else if (held)
6468
174
        {
6469
            // Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop.
6470
            // Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually.
6471
            // FIXME: May want to generalize this idiom at lower-level, so more widgets can use it!
6472
174
            const bool just_scrolled_manually_while_resizing = (g.WheelingWindow != NULL && g.WheelingWindowScrolledFrame == g.FrameCount && IsWindowChildOf(window, g.WheelingWindow, false, true));
6473
174
            if (g.ActiveIdIsJustActivated || just_scrolled_manually_while_resizing)
6474
80
            {
6475
80
                g.WindowResizeBorderExpectedRect = border_rect;
6476
80
                g.WindowResizeRelativeMode = false;
6477
80
            }
6478
174
            if ((window->Flags & ImGuiWindowFlags_ChildWindow) && memcmp(&g.WindowResizeBorderExpectedRect, &border_rect, sizeof(ImRect)) != 0)
6479
0
                g.WindowResizeRelativeMode = true;
6480
6481
174
            const ImVec2 border_curr = (window->Pos + ImMin(def.SegmentN1, def.SegmentN2) * window->Size);
6482
174
            const float border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis];
6483
174
            const float border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING; // Match ButtonBehavior() padding above.
6484
6485
            // Use absolute mode position
6486
174
            ImVec2 border_target = window->Pos;
6487
174
            border_target[axis] = border_target_abs_mode_for_axis;
6488
6489
            // Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position.
6490
174
            bool ignore_resize = false;
6491
174
            if (g.WindowResizeRelativeMode)
6492
0
            {
6493
                //GetForegroundDrawList()->AddText(GetMainViewport()->WorkPos, IM_COL32_WHITE, "Relative Mode");
6494
0
                border_target[axis] = border_target_rel_mode_for_axis;
6495
0
                if (g.IO.MouseDelta[axis] == 0.0f || (g.IO.MouseDelta[axis] > 0.0f) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis))
6496
0
                    ignore_resize = true;
6497
0
            }
6498
6499
            // Clamp, apply
6500
174
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6501
174
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6502
174
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6503
174
            if (flags & ImGuiWindowFlags_ChildWindow) // Clamp resizing of childs within parent
6504
0
            {
6505
0
                ImGuiWindow* parent_window = window->ParentWindow;
6506
0
                ImGuiWindowFlags parent_flags = parent_window->Flags;
6507
0
                ImRect border_limit_rect = parent_window->InnerRect;
6508
0
                border_limit_rect.Expand(ImVec2(-ImMax(parent_window->WindowPadding.x, parent_window->WindowBorderSize), -ImMax(parent_window->WindowPadding.y, parent_window->WindowBorderSize)));
6509
0
                if ((axis == ImGuiAxis_X) && ((parent_flags & (ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) == 0 || (parent_flags & ImGuiWindowFlags_NoScrollbar)))
6510
0
                    border_target.x = ImClamp(border_target.x, border_limit_rect.Min.x, border_limit_rect.Max.x);
6511
0
                if ((axis == ImGuiAxis_Y) && (parent_flags & ImGuiWindowFlags_NoScrollbar))
6512
0
                    border_target.y = ImClamp(border_target.y, border_limit_rect.Min.y, border_limit_rect.Max.y);
6513
0
            }
6514
174
            if (!ignore_resize)
6515
174
                CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6516
174
        }
6517
101k
        if (hovered)
6518
1.14k
            *border_hovered = border_n;
6519
101k
        if (held)
6520
187
            *border_held = border_n;
6521
101k
    }
6522
25.3k
    PopID();
6523
6524
    // Restore nav layer
6525
25.3k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6526
6527
    // Navigation resize (keyboard/gamepad)
6528
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6529
    // Not even sure the callback works here.
6530
25.3k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6531
0
    {
6532
0
        ImVec2 nav_resize_dir;
6533
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6534
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6535
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6536
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6537
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6538
0
        {
6539
0
            const float NAV_RESIZE_SPEED = 600.0f;
6540
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6541
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6542
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6543
0
            g.NavWindowingToggleLayer = false;
6544
0
            g.NavDisableMouseHover = true;
6545
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6546
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaSize);
6547
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6548
0
            {
6549
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6550
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6551
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6552
0
            }
6553
0
        }
6554
0
    }
6555
6556
    // Apply back modified position/size to window
6557
25.3k
    const ImVec2 curr_pos = window->Pos;
6558
25.3k
    const ImVec2 curr_size = window->SizeFull;
6559
25.3k
    if (size_target.x != FLT_MAX && (window->Size.x != size_target.x || window->SizeFull.x != size_target.x))
6560
0
        window->Size.x = window->SizeFull.x = size_target.x;
6561
25.3k
    if (size_target.y != FLT_MAX && (window->Size.y != size_target.y || window->SizeFull.y != size_target.y))
6562
0
        window->Size.y = window->SizeFull.y = size_target.y;
6563
25.3k
    if (pos_target.x != FLT_MAX && window->Pos.x != ImTrunc(pos_target.x))
6564
0
        window->Pos.x = ImTrunc(pos_target.x);
6565
25.3k
    if (pos_target.y != FLT_MAX && window->Pos.y != ImTrunc(pos_target.y))
6566
0
        window->Pos.y = ImTrunc(pos_target.y);
6567
25.3k
    if (curr_pos.x != window->Pos.x || curr_pos.y != window->Pos.y || curr_size.x != window->SizeFull.x || curr_size.y != window->SizeFull.y)
6568
0
        MarkIniSettingsDirty(window);
6569
6570
    // Recalculate next expected border expected coordinates
6571
25.3k
    if (*border_held != -1)
6572
187
        g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, *border_held, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6573
6574
25.3k
    return ret_auto_fit_mask;
6575
105k
}
6576
6577
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6578
161k
{
6579
161k
    ImGuiContext& g = *GImGui;
6580
161k
    ImVec2 size_for_clamping = window->Size;
6581
161k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && window->DockNodeAsHost)
6582
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6583
161k
    else if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6584
0
        size_for_clamping.y = window->TitleBarHeight;
6585
161k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6586
161k
}
6587
6588
static void RenderWindowOuterSingleBorder(ImGuiWindow* window, int border_n, ImU32 border_col, float border_size)
6589
1.15k
{
6590
1.15k
    const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6591
1.15k
    const float rounding = window->WindowRounding;
6592
1.15k
    const ImRect border_r = GetResizeBorderRect(window, border_n, rounding, 0.0f);
6593
1.15k
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6594
1.15k
    window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6595
1.15k
    window->DrawList->PathStroke(border_col, ImDrawFlags_None, border_size);
6596
1.15k
}
6597
6598
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6599
131k
{
6600
131k
    ImGuiContext& g = *GImGui;
6601
131k
    const float border_size = window->WindowBorderSize;
6602
131k
    const ImU32 border_col = GetColorU32(ImGuiCol_Border);
6603
131k
    if (border_size > 0.0f && (window->Flags & ImGuiWindowFlags_NoBackground) == 0)
6604
114k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, border_col, window->WindowRounding, 0, window->WindowBorderSize);
6605
16.3k
    else if (border_size > 0.0f)
6606
0
    {
6607
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeX) // Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border.
6608
0
            RenderWindowOuterSingleBorder(window, 1, border_col, border_size);
6609
0
        if (window->ChildFlags & ImGuiChildFlags_ResizeY)
6610
0
            RenderWindowOuterSingleBorder(window, 3, border_col, border_size);
6611
0
    }
6612
131k
    if (window->ResizeBorderHovered != -1 || window->ResizeBorderHeld != -1)
6613
1.15k
    {
6614
1.15k
        const int border_n = (window->ResizeBorderHeld != -1) ? window->ResizeBorderHeld : window->ResizeBorderHovered;
6615
1.15k
        const ImU32 border_col_resizing = GetColorU32((window->ResizeBorderHeld != -1) ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
6616
1.15k
        RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0f, window->WindowBorderSize)); // Thicker than usual
6617
1.15k
    }
6618
131k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6619
0
    {
6620
0
        float y = window->Pos.y + window->TitleBarHeight - 1;
6621
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), border_col, g.Style.FrameBorderSize);
6622
0
    }
6623
131k
}
6624
6625
// Draw background and borders
6626
// Draw and handle scrollbars
6627
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6628
186k
{
6629
186k
    ImGuiContext& g = *GImGui;
6630
186k
    ImGuiStyle& style = g.Style;
6631
186k
    ImGuiWindowFlags flags = window->Flags;
6632
6633
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6634
186k
    IM_ASSERT(window->BeginCount == 0);
6635
186k
    window->SkipItems = false;
6636
6637
    // Draw window + handle manual resize
6638
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6639
186k
    const float window_rounding = window->WindowRounding;
6640
186k
    const float window_border_size = window->WindowBorderSize;
6641
186k
    if (window->Collapsed)
6642
55.2k
    {
6643
        // Title bar only
6644
55.2k
        const float backup_border_size = style.FrameBorderSize;
6645
55.2k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6646
55.2k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6647
55.2k
        if (window->ViewportOwned)
6648
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6649
55.2k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6650
55.2k
        g.Style.FrameBorderSize = backup_border_size;
6651
55.2k
    }
6652
131k
    else
6653
131k
    {
6654
        // Window background
6655
131k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6656
131k
        {
6657
131k
            bool is_docking_transparent_payload = false;
6658
131k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6659
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6660
0
                    is_docking_transparent_payload = true;
6661
6662
131k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6663
131k
            if (window->ViewportOwned)
6664
0
            {
6665
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6666
0
                if (is_docking_transparent_payload)
6667
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6668
0
            }
6669
131k
            else
6670
131k
            {
6671
                // Adjust alpha. For docking
6672
131k
                bool override_alpha = false;
6673
131k
                float alpha = 1.0f;
6674
131k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6675
0
                {
6676
0
                    alpha = g.NextWindowData.BgAlphaVal;
6677
0
                    override_alpha = true;
6678
0
                }
6679
131k
                if (is_docking_transparent_payload)
6680
0
                {
6681
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6682
0
                    override_alpha = true;
6683
0
                }
6684
131k
                if (override_alpha)
6685
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6686
131k
            }
6687
6688
            // Render, for docked windows and host windows we ensure bg goes before decorations
6689
131k
            if (window->DockIsActive)
6690
0
                window->DockNode->LastBgColor = bg_col;
6691
131k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6692
131k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6693
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6694
131k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6695
131k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6696
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6697
131k
        }
6698
131k
        if (window->DockIsActive)
6699
0
            window->DockNode->IsBgDrawnThisFrame = true;
6700
6701
        // Title bar
6702
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6703
        // in order for their pos/size to be matching their undocking state.)
6704
131k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6705
105k
        {
6706
105k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6707
105k
            if (window->ViewportOwned)
6708
0
                title_bar_col |= IM_COL32_A_MASK; // No alpha
6709
105k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6710
105k
        }
6711
6712
        // Menu bar
6713
131k
        if (flags & ImGuiWindowFlags_MenuBar)
6714
0
        {
6715
0
            ImRect menu_bar_rect = window->MenuBarRect();
6716
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6717
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6718
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6719
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6720
0
        }
6721
6722
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6723
131k
        ImGuiDockNode* node = window->DockNode;
6724
131k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6725
0
        {
6726
0
            float unhide_sz_draw = ImTrunc(g.FontSize * 0.70f);
6727
0
            float unhide_sz_hit = ImTrunc(g.FontSize * 0.55f);
6728
0
            ImVec2 p = node->Pos;
6729
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6730
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6731
0
            KeepAliveID(unhide_id);
6732
0
            bool hovered, held;
6733
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6734
0
                node->WantHiddenTabBarToggle = true;
6735
0
            else if (held && IsMouseDragging(0))
6736
0
                StartMouseMovingWindowOrNode(window, node, true); // Undock from tab-bar triangle = same as window/collapse menu button
6737
6738
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6739
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6740
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6741
0
        }
6742
6743
        // Scrollbars
6744
131k
        if (window->ScrollbarX)
6745
25.3k
            Scrollbar(ImGuiAxis_X);
6746
131k
        if (window->ScrollbarY)
6747
21.5k
            Scrollbar(ImGuiAxis_Y);
6748
6749
        // Render resize grips (after their input handling so we don't have a frame of latency)
6750
131k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6751
105k
        {
6752
317k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6753
211k
            {
6754
211k
                const ImU32 col = resize_grip_col[resize_grip_n];
6755
211k
                if ((col & IM_COL32_A_MASK) == 0)
6756
186k
                    continue;
6757
25.3k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6758
25.3k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6759
25.3k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6760
25.3k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6761
25.3k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6762
25.3k
                window->DrawList->PathFillConvex(col);
6763
25.3k
            }
6764
105k
        }
6765
6766
        // Borders (for dock node host they will be rendered over after the tab bar)
6767
131k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6768
131k
            RenderWindowOuterBorders(window);
6769
131k
    }
6770
186k
}
6771
6772
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6773
// Render title text, collapse button, close button
6774
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6775
161k
{
6776
161k
    ImGuiContext& g = *GImGui;
6777
161k
    ImGuiStyle& style = g.Style;
6778
161k
    ImGuiWindowFlags flags = window->Flags;
6779
6780
161k
    const bool has_close_button = (p_open != NULL);
6781
161k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6782
6783
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6784
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6785
161k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6786
161k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6787
161k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6788
6789
    // Layout buttons
6790
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6791
161k
    float pad_l = style.FramePadding.x;
6792
161k
    float pad_r = style.FramePadding.x;
6793
161k
    float button_sz = g.FontSize;
6794
161k
    ImVec2 close_button_pos;
6795
161k
    ImVec2 collapse_button_pos;
6796
161k
    if (has_close_button)
6797
0
    {
6798
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6799
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6800
0
    }
6801
161k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6802
0
    {
6803
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - button_sz, title_bar_rect.Min.y + style.FramePadding.y);
6804
0
        pad_r += button_sz + style.ItemInnerSpacing.x;
6805
0
    }
6806
161k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6807
161k
    {
6808
161k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y + style.FramePadding.y);
6809
161k
        pad_l += button_sz + style.ItemInnerSpacing.x;
6810
161k
    }
6811
6812
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6813
161k
    if (has_collapse_button)
6814
161k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6815
4
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6816
6817
    // Close button
6818
161k
    if (has_close_button)
6819
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6820
0
            *p_open = false;
6821
6822
161k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6823
161k
    g.CurrentItemFlags = item_flags_backup;
6824
6825
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6826
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6827
161k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6828
161k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6829
6830
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6831
    // while uncentered title text will still reach edges correctly.
6832
161k
    if (pad_l > style.FramePadding.x)
6833
161k
        pad_l += g.Style.ItemInnerSpacing.x;
6834
161k
    if (pad_r > style.FramePadding.x)
6835
0
        pad_r += g.Style.ItemInnerSpacing.x;
6836
161k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6837
0
    {
6838
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6839
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6840
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6841
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6842
0
    }
6843
6844
161k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6845
161k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6846
161k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6847
0
    {
6848
0
        ImVec2 marker_pos;
6849
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6850
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6851
0
        if (marker_pos.x > layout_r.Min.x)
6852
0
        {
6853
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6854
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6855
0
        }
6856
0
    }
6857
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6858
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6859
161k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6860
161k
}
6861
6862
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6863
186k
{
6864
186k
    window->ParentWindow = parent_window;
6865
186k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6866
186k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6867
25.3k
    {
6868
25.3k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6869
25.3k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6870
25.3k
            window->RootWindow = parent_window->RootWindow;
6871
25.3k
    }
6872
186k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6873
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6874
186k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6875
25.3k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6876
186k
    while (window->RootWindowForNav->ChildFlags & ImGuiChildFlags_NavFlattened)
6877
0
    {
6878
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6879
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6880
0
    }
6881
186k
}
6882
6883
// [EXPERIMENTAL] Called by Begin(). NextWindowData is valid at this point.
6884
// This is designed as a toy/test-bed for
6885
void ImGui::UpdateWindowSkipRefresh(ImGuiWindow* window)
6886
186k
{
6887
186k
    ImGuiContext& g = *GImGui;
6888
186k
    window->SkipRefresh = false;
6889
186k
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasRefreshPolicy) == 0)
6890
186k
        return;
6891
0
    if (g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_TryToAvoidRefresh)
6892
0
    {
6893
        // FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused.
6894
0
        if (window->Appearing) // If currently appearing
6895
0
            return;
6896
0
        if (window->Hidden) // If was hidden (previous frame)
6897
0
            return;
6898
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnHover) && g.HoveredWindow && window->RootWindow == g.HoveredWindow->RootWindow)
6899
0
            return;
6900
0
        if ((g.NextWindowData.RefreshFlagsVal & ImGuiWindowRefreshFlags_RefreshOnFocus) && g.NavWindow && window->RootWindow == g.NavWindow->RootWindow)
6901
0
            return;
6902
0
        window->DrawList = NULL;
6903
0
        window->SkipRefresh = true;
6904
0
    }
6905
0
}
6906
6907
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6908
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6909
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6910
// - WindowA            // FindBlockingModal() returns Modal1
6911
//   - WindowB          //                  .. returns Modal1
6912
//   - Modal1           //                  .. returns Modal2
6913
//      - WindowC       //                  .. returns Modal2
6914
//          - WindowD   //                  .. returns Modal2
6915
//          - Modal2    //                  .. returns Modal2
6916
//            - WindowE //                  .. returns NULL
6917
// Notes:
6918
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6919
//   Only difference is here we check for ->Active/WasActive but it may be unnecessary.
6920
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6921
207
{
6922
207
    ImGuiContext& g = *GImGui;
6923
207
    if (g.OpenPopupStack.Size <= 0)
6924
207
        return NULL;
6925
6926
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6927
0
    for (ImGuiPopupData& popup_data : g.OpenPopupStack)
6928
0
    {
6929
0
        ImGuiWindow* popup_window = popup_data.Window;
6930
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6931
0
            continue;
6932
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6933
0
            continue;
6934
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6935
0
            return popup_window;
6936
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6937
0
            continue;
6938
0
        return popup_window;                                        // Place window right below first block modal
6939
0
    }
6940
0
    return NULL;
6941
0
}
6942
6943
// Push a new Dear ImGui window to add widgets to.
6944
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6945
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6946
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6947
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6948
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6949
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6950
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6951
186k
{
6952
186k
    ImGuiContext& g = *GImGui;
6953
186k
    const ImGuiStyle& style = g.Style;
6954
186k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6955
186k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6956
186k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6957
6958
    // Find or create
6959
186k
    ImGuiWindow* window = FindWindowByName(name);
6960
186k
    const bool window_just_created = (window == NULL);
6961
186k
    if (window_just_created)
6962
4
        window = CreateNewWindow(name, flags);
6963
6964
    // [DEBUG] Debug break requested by user
6965
186k
    if (g.DebugBreakInWindow == window->ID)
6966
0
        IM_DEBUG_BREAK();
6967
6968
    // Automatically disable manual moving/resizing when NoInputs is set
6969
186k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6970
3
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6971
6972
186k
    const int current_frame = g.FrameCount;
6973
186k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6974
186k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6975
6976
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6977
186k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6978
186k
    if (flags & ImGuiWindowFlags_Popup)
6979
0
    {
6980
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6981
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6982
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6983
0
    }
6984
6985
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6986
186k
    const bool window_was_appearing = window->Appearing;
6987
186k
    if (first_begin_of_the_frame)
6988
186k
    {
6989
186k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6990
186k
        window->Appearing = window_just_activated_by_user;
6991
186k
        if (window->Appearing)
6992
14
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6993
186k
        window->FlagsPreviousFrame = window->Flags;
6994
186k
        window->Flags = (ImGuiWindowFlags)flags;
6995
186k
        window->ChildFlags = (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : 0;
6996
186k
        window->LastFrameActive = current_frame;
6997
186k
        window->LastTimeActive = (float)g.Time;
6998
186k
        window->BeginOrderWithinParent = 0;
6999
186k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
7000
186k
    }
7001
0
    else
7002
0
    {
7003
0
        flags = window->Flags;
7004
0
    }
7005
7006
    // Docking
7007
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
7008
186k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
7009
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
7010
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
7011
186k
    if (first_begin_of_the_frame)
7012
186k
    {
7013
186k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
7014
186k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
7015
186k
        bool dock_node_was_visible = window->DockNodeIsVisible;
7016
186k
        bool dock_tab_was_visible = window->DockTabIsVisible;
7017
186k
        if (has_dock_node || new_auto_dock_node)
7018
0
        {
7019
0
            BeginDocked(window, p_open);
7020
0
            flags = window->Flags;
7021
0
            if (window->DockIsActive)
7022
0
            {
7023
0
                IM_ASSERT(window->DockNode != NULL);
7024
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
7025
0
            }
7026
7027
            // Amend the Appearing flag
7028
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
7029
0
            {
7030
0
                window->Appearing = true;
7031
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
7032
0
            }
7033
0
        }
7034
186k
        else
7035
186k
        {
7036
186k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
7037
186k
        }
7038
186k
    }
7039
7040
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
7041
186k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
7042
186k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
7043
186k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
7044
7045
    // We allow window memory to be compacted so recreate the base stack when needed.
7046
186k
    if (window->IDStack.Size == 0)
7047
3
        window->IDStack.push_back(window->ID);
7048
7049
    // Add to stack
7050
186k
    g.CurrentWindow = window;
7051
186k
    ImGuiWindowStackData window_stack_data;
7052
186k
    window_stack_data.Window = window;
7053
186k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
7054
186k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
7055
186k
    window_stack_data.DisabledOverrideReenable = (flags & ImGuiWindowFlags_Tooltip) && (g.CurrentItemFlags & ImGuiItemFlags_Disabled);
7056
186k
    g.CurrentWindowStack.push_back(window_stack_data);
7057
186k
    if (flags & ImGuiWindowFlags_ChildMenu)
7058
0
        g.BeginMenuDepth++;
7059
7060
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
7061
186k
    if (first_begin_of_the_frame)
7062
186k
    {
7063
186k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
7064
186k
        window->ParentWindowInBeginStack = parent_window_in_stack;
7065
7066
        // Focus route
7067
        // There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack,
7068
        // Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798)
7069
186k
        window->ParentWindowForFocusRoute = (window->RootWindow != window) ? parent_window_in_stack : NULL;
7070
186k
        if (window->ParentWindowForFocusRoute == NULL && window->DockNode != NULL)
7071
0
            if (window->DockNode->MergedFlags & ImGuiDockNodeFlags_DockedWindowsInFocusRoute)
7072
0
                window->ParentWindowForFocusRoute = window->DockNode->HostWindow;
7073
7074
        // Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute()
7075
186k
        if (window->WindowClass.FocusRouteParentWindowId != 0)
7076
0
        {
7077
0
            window->ParentWindowForFocusRoute = FindWindowByID(window->WindowClass.FocusRouteParentWindowId);
7078
0
            IM_ASSERT(window->ParentWindowForFocusRoute != 0); // Invalid value for FocusRouteParentWindowId.
7079
0
        }
7080
186k
    }
7081
7082
    // Add to focus scope stack
7083
186k
    PushFocusScope((window->ChildFlags & ImGuiChildFlags_NavFlattened) ? g.CurrentFocusScopeId : window->ID);
7084
186k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
7085
7086
    // Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[]
7087
186k
    if (flags & ImGuiWindowFlags_Popup)
7088
0
    {
7089
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
7090
0
        popup_ref.Window = window;
7091
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
7092
0
        g.BeginPopupStack.push_back(popup_ref);
7093
0
        window->PopupId = popup_ref.PopupId;
7094
0
    }
7095
7096
    // Process SetNextWindow***() calls
7097
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
7098
186k
    bool window_pos_set_by_api = false;
7099
186k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
7100
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
7101
0
    {
7102
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
7103
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
7104
0
        {
7105
            // May be processed on the next frame if this is our first frame and we are measuring size
7106
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
7107
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
7108
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
7109
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7110
0
        }
7111
0
        else
7112
0
        {
7113
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
7114
0
        }
7115
0
    }
7116
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
7117
105k
    {
7118
105k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
7119
105k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
7120
105k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeX) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0) // Axis-specific conditions for BeginChild()
7121
0
            g.NextWindowData.SizeVal.x = window->SizeFull.x;
7122
105k
        if ((window->ChildFlags & ImGuiChildFlags_ResizeY) && (window->SetWindowSizeAllowFlags & ImGuiCond_FirstUseEver) == 0)
7123
0
            g.NextWindowData.SizeVal.y = window->SizeFull.y;
7124
105k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
7125
105k
    }
7126
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
7127
0
    {
7128
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
7129
0
        {
7130
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
7131
0
            window->ScrollTargetCenterRatio.x = 0.0f;
7132
0
        }
7133
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
7134
0
        {
7135
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
7136
0
            window->ScrollTargetCenterRatio.y = 0.0f;
7137
0
        }
7138
0
    }
7139
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
7140
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
7141
186k
    else if (first_begin_of_the_frame)
7142
186k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
7143
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
7144
0
        window->WindowClass = g.NextWindowData.WindowClass;
7145
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
7146
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
7147
186k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
7148
0
        FocusWindow(window);
7149
186k
    if (window->Appearing)
7150
14
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
7151
7152
    // [EXPERIMENTAL] Skip Refresh mode
7153
186k
    UpdateWindowSkipRefresh(window);
7154
7155
    // Nested root windows (typically tooltips) override disabled state
7156
186k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7157
0
        BeginDisabledOverrideReenable();
7158
7159
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
7160
186k
    g.CurrentWindow = NULL;
7161
7162
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
7163
186k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7164
186k
    {
7165
        // Initialize
7166
186k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
7167
186k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
7168
186k
        window->Active = true;
7169
186k
        window->HasCloseButton = (p_open != NULL);
7170
186k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
7171
186k
        window->IDStack.resize(1);
7172
186k
        window->DrawList->_ResetForNewFrame();
7173
186k
        window->DC.CurrentTableIdx = -1;
7174
186k
        if (flags & ImGuiWindowFlags_DockNodeHost)
7175
0
        {
7176
0
            window->DrawList->ChannelsSplit(2);
7177
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
7178
0
        }
7179
7180
        // Restore buffer capacity when woken from a compacted state, to avoid
7181
186k
        if (window->MemoryCompacted)
7182
3
            GcAwakeTransientWindowBuffers(window);
7183
7184
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
7185
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
7186
186k
        bool window_title_visible_elsewhere = false;
7187
186k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
7188
0
            window_title_visible_elsewhere = true;
7189
186k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
7190
0
            window_title_visible_elsewhere = true;
7191
186k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
7192
0
        {
7193
0
            size_t buf_len = (size_t)window->NameBufLen;
7194
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
7195
0
            window->NameBufLen = (int)buf_len;
7196
0
        }
7197
7198
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
7199
7200
        // Update contents size from last frame for auto-fitting (or use explicit size)
7201
186k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
7202
7203
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
7204
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
7205
        // it has a single usage before this code block and may be set below before it is finally checked.
7206
186k
        if (window->HiddenFramesCanSkipItems > 0)
7207
301
            window->HiddenFramesCanSkipItems--;
7208
186k
        if (window->HiddenFramesCannotSkipItems > 0)
7209
3
            window->HiddenFramesCannotSkipItems--;
7210
186k
        if (window->HiddenFramesForRenderOnly > 0)
7211
0
            window->HiddenFramesForRenderOnly--;
7212
7213
        // Hide new windows for one frame until they calculate their size
7214
186k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
7215
2
            window->HiddenFramesCannotSkipItems = 1;
7216
7217
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
7218
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
7219
186k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
7220
2
        {
7221
2
            window->HiddenFramesCannotSkipItems = 1;
7222
2
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
7223
2
            {
7224
2
                if (!window_size_x_set_by_api)
7225
2
                    window->Size.x = window->SizeFull.x = 0.f;
7226
2
                if (!window_size_y_set_by_api)
7227
2
                    window->Size.y = window->SizeFull.y = 0.f;
7228
2
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
7229
2
            }
7230
2
        }
7231
7232
        // SELECT VIEWPORT
7233
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
7234
7235
186k
        WindowSelectViewport(window);
7236
186k
        SetCurrentViewport(window, window->Viewport);
7237
186k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7238
186k
        SetCurrentWindow(window);
7239
186k
        flags = window->Flags;
7240
7241
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
7242
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
7243
7244
186k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow))
7245
25.3k
            window->WindowBorderSize = style.ChildBorderSize;
7246
161k
        else
7247
161k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
7248
186k
        window->WindowPadding = style.WindowPadding;
7249
186k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !(window->ChildFlags & ImGuiChildFlags_AlwaysUseWindowPadding) && window->WindowBorderSize == 0.0f)
7250
16.3k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
7251
7252
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
7253
186k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
7254
186k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
7255
186k
        window->TitleBarHeight = (flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : g.FontSize + g.Style.FramePadding.y * 2.0f;
7256
186k
        window->MenuBarHeight = (flags & ImGuiWindowFlags_MenuBar) ? window->DC.MenuBarOffset.y + g.FontSize + g.Style.FramePadding.y * 2.0f : 0.0f;
7257
7258
        // Depending on condition we use previous or current window size to compare against contents size to decide if a scrollbar should be visible.
7259
        // Those flags will be altered further down in the function depending on more conditions.
7260
186k
        bool use_current_size_for_scrollbar_x = window_just_created;
7261
186k
        bool use_current_size_for_scrollbar_y = window_just_created;
7262
186k
        if (window_size_x_set_by_api && window->ContentSizeExplicit.x != 0.0f)
7263
0
            use_current_size_for_scrollbar_x = true;
7264
186k
        if (window_size_y_set_by_api && window->ContentSizeExplicit.y != 0.0f) // #7252
7265
0
            use_current_size_for_scrollbar_y = true;
7266
7267
        // Collapse window by double-clicking on title bar
7268
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
7269
186k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
7270
161k
        {
7271
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
7272
161k
            ImRect title_bar_rect = window->TitleBarRect();
7273
161k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
7274
10.4k
                if (g.IO.MouseClickedCount[0] == 2 && GetKeyOwner(ImGuiKey_MouseLeft) == ImGuiKeyOwner_NoOwner)
7275
16
                    window->WantCollapseToggle = true;
7276
161k
            if (window->WantCollapseToggle)
7277
20
            {
7278
20
                window->Collapsed = !window->Collapsed;
7279
20
                if (!window->Collapsed)
7280
10
                    use_current_size_for_scrollbar_y = true;
7281
20
                MarkIniSettingsDirty(window);
7282
20
            }
7283
161k
        }
7284
25.3k
        else
7285
25.3k
        {
7286
25.3k
            window->Collapsed = false;
7287
25.3k
        }
7288
186k
        window->WantCollapseToggle = false;
7289
7290
        // SIZE
7291
7292
        // Outer Decoration Sizes
7293
        // (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations).
7294
186k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
7295
186k
        window->DecoOuterSizeX1 = 0.0f;
7296
186k
        window->DecoOuterSizeX2 = 0.0f;
7297
186k
        window->DecoOuterSizeY1 = window->TitleBarHeight + window->MenuBarHeight;
7298
186k
        window->DecoOuterSizeY2 = 0.0f;
7299
186k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
7300
7301
        // Calculate auto-fit size, handle automatic resize
7302
186k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
7303
186k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
7304
3
        {
7305
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
7306
3
            if (!window_size_x_set_by_api)
7307
3
            {
7308
3
                window->SizeFull.x = size_auto_fit.x;
7309
3
                use_current_size_for_scrollbar_x = true;
7310
3
            }
7311
3
            if (!window_size_y_set_by_api)
7312
3
            {
7313
3
                window->SizeFull.y = size_auto_fit.y;
7314
3
                use_current_size_for_scrollbar_y = true;
7315
3
            }
7316
3
        }
7317
186k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7318
2
        {
7319
            // Auto-fit may only grow window during the first few frames
7320
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
7321
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
7322
2
            {
7323
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
7324
2
                use_current_size_for_scrollbar_x = true;
7325
2
            }
7326
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
7327
2
            {
7328
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
7329
2
                use_current_size_for_scrollbar_y = true;
7330
2
            }
7331
2
            if (!window->Collapsed)
7332
2
                MarkIniSettingsDirty(window);
7333
2
        }
7334
7335
        // Apply minimum/maximum window size constraints and final size
7336
186k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
7337
186k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
7338
7339
        // POSITION
7340
7341
        // Popup latch its initial position, will position itself when it appears next frame
7342
186k
        if (window_just_activated_by_user)
7343
14
        {
7344
14
            window->AutoPosLastDirection = ImGuiDir_None;
7345
14
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
7346
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
7347
14
        }
7348
7349
        // Position child window
7350
186k
        if (flags & ImGuiWindowFlags_ChildWindow)
7351
25.3k
        {
7352
25.3k
            IM_ASSERT(parent_window && parent_window->Active);
7353
25.3k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
7354
25.3k
            parent_window->DC.ChildWindows.push_back(window);
7355
25.3k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
7356
25.3k
                window->Pos = parent_window->DC.CursorPos;
7357
25.3k
        }
7358
7359
186k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
7360
186k
        if (window_pos_with_pivot)
7361
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
7362
186k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
7363
0
            window->Pos = FindBestWindowPosForPopup(window);
7364
186k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
7365
0
            window->Pos = FindBestWindowPosForPopup(window);
7366
186k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
7367
3
            window->Pos = FindBestWindowPosForPopup(window);
7368
7369
        // Late create viewport if we don't fit within our current host viewport.
7370
186k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
7371
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
7372
0
            {
7373
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
7374
                //ImGuiViewport* old_viewport = window->Viewport;
7375
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
7376
7377
                // FIXME-DPI
7378
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
7379
0
                SetCurrentViewport(window, window->Viewport);
7380
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
7381
0
                SetCurrentWindow(window);
7382
0
            }
7383
7384
186k
        if (window->ViewportOwned)
7385
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
7386
7387
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
7388
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
7389
186k
        ImRect viewport_rect(window->Viewport->GetMainRect());
7390
186k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
7391
186k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
7392
186k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
7393
7394
        // Clamp position/size so window stays visible within its viewport or monitor
7395
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
7396
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
7397
186k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
7398
161k
        {
7399
161k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
7400
161k
            {
7401
161k
                ClampWindowPos(window, visibility_rect);
7402
161k
            }
7403
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7404
0
            {
7405
0
                if (g.MovingWindow != NULL && window->RootWindowDockTree == g.MovingWindow->RootWindowDockTree)
7406
0
                {
7407
                    // While moving windows we allow them to straddle monitors (#7299, #3071)
7408
0
                    visibility_rect = g.PlatformMonitorsFullWorkRect;
7409
0
                }
7410
0
                else
7411
0
                {
7412
                    // When not moving ensure visible in its monitor
7413
                    // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7414
0
                    const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7415
0
                    visibility_rect = ImRect(monitor->WorkPos, monitor->WorkPos + monitor->WorkSize);
7416
0
                }
7417
0
                visibility_rect.Expand(-visibility_padding);
7418
0
                ClampWindowPos(window, visibility_rect);
7419
0
            }
7420
161k
        }
7421
186k
        window->Pos = ImTrunc(window->Pos);
7422
7423
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7424
        // Large values tend to lead to variety of artifacts and are not recommended.
7425
186k
        if (window->ViewportOwned || window->DockIsActive)
7426
0
            window->WindowRounding = 0.0f;
7427
186k
        else
7428
186k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7429
7430
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7431
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7432
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7433
7434
        // Apply window focus (new and reactivated windows are moved to front)
7435
186k
        bool want_focus = false;
7436
186k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7437
14
        {
7438
14
            if (flags & ImGuiWindowFlags_Popup)
7439
0
                want_focus = true;
7440
14
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7441
2
                want_focus = true;
7442
14
        }
7443
7444
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7445
#ifdef IMGUI_ENABLE_TEST_ENGINE
7446
        if (g.TestEngineHookItems)
7447
        {
7448
            IM_ASSERT(window->IDStack.Size == 1);
7449
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7450
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7451
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7452
            window->IDStack.Size = 1;
7453
        }
7454
#endif
7455
7456
        // Decide if we are going to handle borders and resize grips
7457
186k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7458
7459
        // Handle manual resize: Resize Grips, Borders, Gamepad
7460
186k
        int border_hovered = -1, border_held = -1;
7461
186k
        ImU32 resize_grip_col[4] = {};
7462
186k
        const int resize_grip_count = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) ? 0 : g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7463
186k
        const float resize_grip_draw_size = IM_TRUNC(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7464
186k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7465
131k
            if (int auto_fit_mask = UpdateWindowManualResize(window, size_auto_fit, &border_hovered, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7466
0
            {
7467
0
                if (auto_fit_mask & (1 << ImGuiAxis_X))
7468
0
                    use_current_size_for_scrollbar_x = true;
7469
0
                if (auto_fit_mask & (1 << ImGuiAxis_Y))
7470
0
                    use_current_size_for_scrollbar_y = true;
7471
0
            }
7472
186k
        window->ResizeBorderHovered = (signed char)border_hovered;
7473
186k
        window->ResizeBorderHeld = (signed char)border_held;
7474
7475
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7476
186k
        if (window->ViewportOwned)
7477
0
        {
7478
0
            if (!window->Viewport->PlatformRequestMove)
7479
0
                window->Viewport->Pos = window->Pos;
7480
0
            if (!window->Viewport->PlatformRequestResize)
7481
0
                window->Viewport->Size = window->Size;
7482
0
            window->Viewport->UpdateWorkRect();
7483
0
            viewport_rect = window->Viewport->GetMainRect();
7484
0
        }
7485
7486
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7487
186k
        window->ViewportPos = window->Viewport->Pos;
7488
7489
        // SCROLLBAR VISIBILITY
7490
7491
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7492
186k
        if (!window->Collapsed)
7493
131k
        {
7494
            // When reading the current size we need to read it after size constraints have been applied.
7495
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7496
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7497
131k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7498
131k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7499
131k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7500
131k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7501
131k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7502
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7503
131k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7504
131k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7505
131k
            if (window->ScrollbarX && !window->ScrollbarY)
7506
4.24k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
7507
131k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7508
7509
            // Amend the partially filled window->DecorationXXX values.
7510
131k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7511
131k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7512
131k
        }
7513
7514
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7515
        // Update various regions. Variables they depend on should be set above in this function.
7516
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7517
7518
        // Outer rectangle
7519
        // Not affected by window border size. Used by:
7520
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7521
        // - Begin() initial clipping rect for drawing window background and borders.
7522
        // - Begin() clipping whole child
7523
186k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7524
186k
        const ImRect outer_rect = window->Rect();
7525
186k
        const ImRect title_bar_rect = window->TitleBarRect();
7526
186k
        window->OuterRectClipped = outer_rect;
7527
186k
        if (window->DockIsActive)
7528
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight;
7529
186k
        window->OuterRectClipped.ClipWith(host_rect);
7530
7531
        // Inner rectangle
7532
        // Not affected by window border size. Used by:
7533
        // - InnerClipRect
7534
        // - ScrollToRectEx()
7535
        // - NavUpdatePageUpPageDown()
7536
        // - Scrollbar()
7537
186k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7538
186k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7539
186k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7540
186k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7541
7542
        // Inner clipping rectangle.
7543
        // - Extend a outside of normal work region up to borders.
7544
        // - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7545
        // - It also makes clipped items be more noticeable.
7546
        // - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5f on left and right edge), see #3312
7547
        // - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7548
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7549
        // Affected by window/frame border size. Used by:
7550
        // - Begin() initial clip rect
7551
186k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7552
186k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + window->WindowBorderSize);
7553
186k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7554
186k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - window->WindowBorderSize);
7555
186k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7556
186k
        window->InnerClipRect.ClipWithFull(host_rect);
7557
7558
        // Default item width. Make it proportional to window size if window manually resizes
7559
186k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7560
186k
            window->ItemWidthDefault = ImTrunc(window->Size.x * 0.65f);
7561
3
        else
7562
3
            window->ItemWidthDefault = ImTrunc(g.FontSize * 16.0f);
7563
7564
        // SCROLLING
7565
7566
        // Lock down maximum scrolling
7567
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7568
        // for right/bottom aligned items without creating a scrollbar.
7569
186k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7570
186k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7571
7572
        // Apply scrolling
7573
186k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7574
186k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7575
186k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7576
7577
        // DRAWING
7578
7579
        // Setup draw list and outer clipping rectangle
7580
186k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7581
186k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7582
186k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7583
7584
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7585
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7586
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7587
186k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7588
186k
        if (is_undocked_or_docked_visible)
7589
186k
        {
7590
186k
            bool render_decorations_in_parent = false;
7591
186k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7592
25.3k
            {
7593
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7594
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7595
25.3k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7596
25.3k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7597
25.3k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7598
25.3k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7599
25.3k
                    render_decorations_in_parent = true;
7600
25.3k
            }
7601
186k
            if (render_decorations_in_parent)
7602
25.3k
                window->DrawList = parent_window->DrawList;
7603
7604
            // Handle title bar, scrollbar, resize grips and resize borders
7605
186k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7606
186k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7607
186k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7608
7609
186k
            if (render_decorations_in_parent)
7610
25.3k
                window->DrawList = &window->DrawListInst;
7611
186k
        }
7612
7613
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7614
7615
        // Work rectangle.
7616
        // Affected by window padding and border size. Used by:
7617
        // - Columns() for right-most edge
7618
        // - TreeNode(), CollapsingHeader() for right-most edge
7619
        // - BeginTabBar() for right-most edge
7620
186k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7621
186k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7622
186k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7623
186k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7624
186k
        window->WorkRect.Min.x = ImTrunc(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7625
186k
        window->WorkRect.Min.y = ImTrunc(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7626
186k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7627
186k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7628
186k
        window->ParentWorkRect = window->WorkRect;
7629
7630
        // [LEGACY] Content Region
7631
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7632
        // Unless explicit content size is specified by user, this currently represent the region leading to no scrolling.
7633
        // Used by:
7634
        // - Mouse wheel scrolling + many other things
7635
186k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7636
186k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7637
186k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7638
186k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7639
7640
        // Setup drawing context
7641
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7642
186k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7643
186k
        window->DC.GroupOffset.x = 0.0f;
7644
186k
        window->DC.ColumnsOffset.x = 0.0f;
7645
7646
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7647
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7648
186k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7649
186k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7650
186k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7651
186k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7652
186k
        window->DC.CursorPos = window->DC.CursorStartPos;
7653
186k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7654
186k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7655
186k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7656
186k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7657
186k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7658
186k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7659
7660
186k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7661
186k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7662
186k
        window->DC.NavLayersActiveMaskNext = 0x00;
7663
186k
        window->DC.NavIsScrollPushableX = true;
7664
186k
        window->DC.NavHideHighlightOneFrame = false;
7665
186k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7666
7667
186k
        window->DC.MenuBarAppending = false;
7668
186k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7669
186k
        window->DC.TreeDepth = 0;
7670
186k
        window->DC.TreeHasStackDataDepthMask = 0x00;
7671
186k
        window->DC.ChildWindows.resize(0);
7672
186k
        window->DC.StateStorage = &window->StateStorage;
7673
186k
        window->DC.CurrentColumns = NULL;
7674
186k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7675
186k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7676
7677
186k
        window->DC.ItemWidth = window->ItemWidthDefault;
7678
186k
        window->DC.TextWrapPos = -1.0f; // disabled
7679
186k
        window->DC.ItemWidthStack.resize(0);
7680
186k
        window->DC.TextWrapPosStack.resize(0);
7681
186k
        if (flags & ImGuiWindowFlags_Modal)
7682
0
            window->DC.ModalDimBgColor = ColorConvertFloat4ToU32(GetStyleColorVec4(ImGuiCol_ModalWindowDimBg));
7683
7684
186k
        if (window->AutoFitFramesX > 0)
7685
4
            window->AutoFitFramesX--;
7686
186k
        if (window->AutoFitFramesY > 0)
7687
4
            window->AutoFitFramesY--;
7688
7689
        // Clear SetNextWindowXXX data (can aim to move this higher in the function)
7690
186k
        g.NextWindowData.ClearFlags();
7691
7692
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7693
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7694
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7695
        // - Position window behind the modal that is not a begin-parent of this window.
7696
186k
        if (want_focus)
7697
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7698
186k
        if (want_focus && window == g.NavWindow)
7699
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7700
7701
        // Close requested by platform window (apply to all windows in this viewport)
7702
186k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7703
0
        {
7704
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7705
0
            *p_open = false;
7706
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7707
0
        }
7708
7709
        // Title bar
7710
186k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7711
161k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7712
7713
        // Clear hit test shape every frame
7714
186k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7715
7716
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7717
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7718
        // Maybe we can support CTRL+C on every element?
7719
        /*
7720
        //if (g.NavWindow == window && g.ActiveId == 0)
7721
        if (g.ActiveId == window->MoveId)
7722
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7723
                LogToClipboard();
7724
        */
7725
7726
186k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7727
186k
        {
7728
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7729
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7730
186k
            if (g.MovingWindow == window && (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7731
4.96k
                BeginDockableDragDropSource(window);
7732
7733
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7734
186k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7735
6.99k
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7736
3.51k
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7737
3.51k
                        BeginDockableDragDropTarget(window);
7738
186k
        }
7739
7740
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7741
        // This is useful to allow creating context menus on title bar only, etc.
7742
186k
        SetLastItemDataForWindow(window, title_bar_rect);
7743
7744
        // [DEBUG]
7745
186k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7746
186k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7747
0
            DebugLocateItemResolveWithLastItem();
7748
186k
#endif
7749
7750
        // [Test Engine] Register title bar / tab with MoveId.
7751
#ifdef IMGUI_ENABLE_TEST_ENGINE
7752
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7753
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7754
#endif
7755
186k
    }
7756
0
    else
7757
0
    {
7758
        // Skip refresh always mark active
7759
0
        if (window->SkipRefresh)
7760
0
            window->Active = true;
7761
7762
        // Append
7763
0
        SetCurrentViewport(window, window->Viewport);
7764
0
        SetCurrentWindow(window);
7765
0
        g.NextWindowData.ClearFlags();
7766
0
        SetLastItemDataForWindow(window, window->TitleBarRect());
7767
0
    }
7768
7769
186k
    if (!(flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)
7770
186k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7771
7772
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7773
186k
    window->WriteAccessed = false;
7774
186k
    window->BeginCount++;
7775
7776
    // Update visibility
7777
186k
    if (first_begin_of_the_frame && !window->SkipRefresh)
7778
186k
    {
7779
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7780
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7781
        // This is analogous to regular windows being hidden from one frame.
7782
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7783
186k
        if (window->DockIsActive && !window->DockTabIsVisible)
7784
0
        {
7785
0
            if (window->LastFrameJustFocused == g.FrameCount)
7786
0
                window->HiddenFramesCannotSkipItems = 1;
7787
0
            else
7788
0
                window->HiddenFramesCanSkipItems = 1;
7789
0
        }
7790
7791
186k
        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ChildMenu))
7792
25.3k
        {
7793
            // Child window can be out of sight and have "negative" clip windows.
7794
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7795
25.3k
            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || window->DockIsActive);
7796
25.3k
            const bool nav_request = (window->ChildFlags & ImGuiChildFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7797
25.3k
            if (!g.LogEnabled && !nav_request)
7798
25.3k
                if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7799
301
                {
7800
301
                    if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
7801
0
                        window->HiddenFramesCannotSkipItems = 1;
7802
301
                    else
7803
301
                        window->HiddenFramesCanSkipItems = 1;
7804
301
                }
7805
7806
            // Hide along with parent or if parent is collapsed
7807
25.3k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7808
0
                window->HiddenFramesCanSkipItems = 1;
7809
25.3k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7810
1
                window->HiddenFramesCannotSkipItems = 1;
7811
25.3k
        }
7812
7813
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7814
186k
        if (style.Alpha <= 0.0f)
7815
0
            window->HiddenFramesCanSkipItems = 1;
7816
7817
        // Update the Hidden flag
7818
186k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7819
186k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7820
7821
        // Disable inputs for requested number of frames
7822
186k
        if (window->DisableInputsFrames > 0)
7823
0
        {
7824
0
            window->DisableInputsFrames--;
7825
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7826
0
        }
7827
7828
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7829
186k
        bool skip_items = false;
7830
186k
        if (window->Collapsed || !window->Active || hidden_regular)
7831
55.5k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7832
55.5k
                skip_items = true;
7833
186k
        window->SkipItems = skip_items;
7834
7835
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7836
186k
        if (window->SkipItems)
7837
55.5k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7838
7839
        // Sanity check: there are two spots which can set Appearing = true
7840
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7841
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7842
186k
        if (window->SkipItems && !window->Appearing)
7843
186k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7844
186k
    }
7845
0
    else if (first_begin_of_the_frame)
7846
0
    {
7847
        // Skip refresh mode
7848
0
        window->SkipItems = true;
7849
0
    }
7850
7851
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7852
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7853
186k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7854
186k
    if (!window->IsFallbackWindow)
7855
105k
        if ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size))
7856
0
        {
7857
0
            if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7858
0
            if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7859
0
            return false;
7860
0
        }
7861
186k
#endif
7862
7863
186k
    return !window->SkipItems;
7864
186k
}
7865
7866
static void ImGui::SetLastItemDataForWindow(ImGuiWindow* window, const ImRect& rect)
7867
186k
{
7868
186k
    ImGuiContext& g = *GImGui;
7869
186k
    if (window->DockIsActive)
7870
0
        SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7871
186k
    else
7872
186k
        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(rect.Min, rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, rect);
7873
186k
}
7874
7875
void ImGui::End()
7876
186k
{
7877
186k
    ImGuiContext& g = *GImGui;
7878
186k
    ImGuiWindow* window = g.CurrentWindow;
7879
7880
    // Error checking: verify that user hasn't called End() too many times!
7881
186k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7882
0
    {
7883
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7884
0
        return;
7885
0
    }
7886
186k
    ImGuiWindowStackData& window_stack_data = g.CurrentWindowStack.back();
7887
7888
    // Error checking: verify that user doesn't directly call End() on a child window.
7889
186k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7890
186k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7891
7892
    // Close anything that is open
7893
186k
    if (window->DC.CurrentColumns)
7894
0
        EndColumns();
7895
186k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->SkipRefresh)   // Pop inner window clip rectangle
7896
186k
        PopClipRect();
7897
186k
    PopFocusScope();
7898
186k
    if (window_stack_data.DisabledOverrideReenable && window->RootWindow == window)
7899
0
        EndDisabledOverrideReenable();
7900
7901
186k
    if (window->SkipRefresh)
7902
0
    {
7903
0
        IM_ASSERT(window->DrawList == NULL);
7904
0
        window->DrawList = &window->DrawListInst;
7905
0
    }
7906
7907
    // Stop logging
7908
186k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7909
161k
        LogFinish();
7910
7911
186k
    if (window->DC.IsSetPos)
7912
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7913
7914
    // Docking: report contents sizes to parent to allow for auto-resize
7915
186k
    if (window->DockNode && window->DockTabIsVisible)
7916
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7917
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7918
7919
    // Pop from window stack
7920
186k
    g.LastItemData = window_stack_data.ParentLastItemDataBackup;
7921
186k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7922
0
        g.BeginMenuDepth--;
7923
186k
    if (window->Flags & ImGuiWindowFlags_Popup)
7924
0
        g.BeginPopupStack.pop_back();
7925
186k
    window_stack_data.StackSizesOnBegin.CompareWithContextState(&g);
7926
186k
    g.CurrentWindowStack.pop_back();
7927
186k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7928
186k
    if (g.CurrentWindow)
7929
105k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7930
186k
}
7931
7932
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7933
11.6k
{
7934
11.6k
    ImGuiContext& g = *GImGui;
7935
11.6k
    IM_ASSERT(window == window->RootWindow);
7936
7937
11.6k
    const int cur_order = window->FocusOrder;
7938
11.6k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7939
11.6k
    if (g.WindowsFocusOrder.back() == window)
7940
11.6k
        return;
7941
7942
1
    const int new_order = g.WindowsFocusOrder.Size - 1;
7943
2
    for (int n = cur_order; n < new_order; n++)
7944
1
    {
7945
1
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7946
1
        g.WindowsFocusOrder[n]->FocusOrder--;
7947
1
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7948
1
    }
7949
1
    g.WindowsFocusOrder[new_order] = window;
7950
1
    window->FocusOrder = (short)new_order;
7951
1
}
7952
7953
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7954
11.6k
{
7955
11.6k
    ImGuiContext& g = *GImGui;
7956
11.6k
    ImGuiWindow* current_front_window = g.Windows.back();
7957
11.6k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7958
11.6k
        return;
7959
2
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7960
2
        if (g.Windows[i] == window)
7961
1
        {
7962
1
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7963
1
            g.Windows[g.Windows.Size - 1] = window;
7964
1
            break;
7965
1
        }
7966
1
}
7967
7968
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7969
0
{
7970
0
    ImGuiContext& g = *GImGui;
7971
0
    if (g.Windows[0] == window)
7972
0
        return;
7973
0
    for (int i = 0; i < g.Windows.Size; i++)
7974
0
        if (g.Windows[i] == window)
7975
0
        {
7976
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7977
0
            g.Windows[0] = window;
7978
0
            break;
7979
0
        }
7980
0
}
7981
7982
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7983
0
{
7984
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7985
0
    ImGuiContext& g = *GImGui;
7986
0
    window = window->RootWindow;
7987
0
    behind_window = behind_window->RootWindow;
7988
0
    int pos_wnd = FindWindowDisplayIndex(window);
7989
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7990
0
    if (pos_wnd < pos_beh)
7991
0
    {
7992
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7993
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7994
0
        g.Windows[pos_beh - 1] = window;
7995
0
    }
7996
0
    else
7997
0
    {
7998
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7999
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
8000
0
        g.Windows[pos_beh] = window;
8001
0
    }
8002
0
}
8003
8004
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
8005
0
{
8006
0
    ImGuiContext& g = *GImGui;
8007
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
8008
0
}
8009
8010
// Moving window to front of display and set focus (which happens to be back of our sorted list)
8011
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
8012
21.6k
{
8013
21.6k
    ImGuiContext& g = *GImGui;
8014
8015
    // Modal check?
8016
21.6k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
8017
207
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
8018
0
        {
8019
            // This block would typically be reached in two situations:
8020
            // - API call to FocusWindow() with a window under a modal and ImGuiFocusRequestFlags_UnlessBelowModal flag.
8021
            // - User clicking on void or anything behind a modal while a modal is open (window == NULL)
8022
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
8023
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8024
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring right under modal. (FIXME: Could move in focus list too?)
8025
0
            ClosePopupsOverWindow(GetTopMostPopupModal(), false); // Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals
8026
0
            return;
8027
0
        }
8028
8029
    // Find last focused child (if any) and focus it instead.
8030
21.6k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
8031
94
        window = NavRestoreLastChildNavWindow(window);
8032
8033
    // Apply focus
8034
21.6k
    if (g.NavWindow != window)
8035
6.85k
    {
8036
6.85k
        SetNavWindow(window);
8037
6.85k
        if (window && g.NavDisableMouseHover)
8038
465
            g.NavMousePosDirty = true;
8039
6.85k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
8040
6.85k
        g.NavLayer = ImGuiNavLayer_Main;
8041
6.85k
        SetNavFocusScope(window ? window->NavRootFocusScopeId : 0);
8042
6.85k
        g.NavIdIsAlive = false;
8043
6.85k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
8044
8045
        // Close popups if any
8046
6.85k
        ClosePopupsOverWindow(window, false);
8047
6.85k
    }
8048
8049
    // Move the root window to the top of the pile
8050
21.6k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
8051
21.6k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
8052
21.6k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
8053
21.6k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
8054
21.6k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
8055
8056
    // Steal active widgets. Some of the cases it triggers includes:
8057
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
8058
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
8059
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
8060
21.6k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
8061
787
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
8062
18
            ClearActiveID();
8063
8064
    // Passing NULL allow to disable keyboard focus
8065
21.6k
    if (!window)
8066
9.90k
        return;
8067
11.6k
    window->LastFrameJustFocused = g.FrameCount;
8068
8069
    // Select in dock node
8070
    // For #2304 we avoid applying focus immediately before the tabbar is visible.
8071
    //if (dock_node && dock_node->TabBar)
8072
    //    dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
8073
8074
    // Bring to front
8075
11.6k
    BringWindowToFocusFront(focus_front_window);
8076
11.6k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
8077
11.6k
        BringWindowToDisplayFront(display_front_window);
8078
11.6k
}
8079
8080
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
8081
1
{
8082
1
    ImGuiContext& g = *GImGui;
8083
1
    int start_idx = g.WindowsFocusOrder.Size - 1;
8084
1
    if (under_this_window != NULL)
8085
0
    {
8086
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
8087
0
        int offset = -1;
8088
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
8089
0
        {
8090
0
            under_this_window = under_this_window->ParentWindow;
8091
0
            offset = 0;
8092
0
        }
8093
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
8094
0
    }
8095
1
    for (int i = start_idx; i >= 0; i--)
8096
1
    {
8097
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
8098
1
        ImGuiWindow* window = g.WindowsFocusOrder[i];
8099
1
        if (window == ignore_window || !window->WasActive)
8100
0
            continue;
8101
1
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
8102
0
            continue;
8103
1
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
8104
1
        {
8105
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
8106
            // This is failing (lagging by one frame) for docked windows.
8107
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
8108
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
8109
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
8110
1
            FocusWindow(window, flags);
8111
1
            return;
8112
1
        }
8113
1
    }
8114
0
    FocusWindow(NULL, flags);
8115
0
}
8116
8117
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
8118
void ImGui::SetCurrentFont(ImFont* font)
8119
80.5k
{
8120
80.5k
    ImGuiContext& g = *GImGui;
8121
80.5k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
8122
80.5k
    IM_ASSERT(font->Scale > 0.0f);
8123
80.5k
    g.Font = font;
8124
80.5k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
8125
80.5k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
8126
80.5k
    g.FontScale = g.FontSize / g.Font->FontSize;
8127
8128
80.5k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
8129
80.5k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
8130
80.5k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
8131
80.5k
    g.DrawListSharedData.Font = g.Font;
8132
80.5k
    g.DrawListSharedData.FontSize = g.FontSize;
8133
80.5k
    g.DrawListSharedData.FontScale = g.FontScale;
8134
80.5k
}
8135
8136
void ImGui::PushFont(ImFont* font)
8137
0
{
8138
0
    ImGuiContext& g = *GImGui;
8139
0
    if (!font)
8140
0
        font = GetDefaultFont();
8141
0
    SetCurrentFont(font);
8142
0
    g.FontStack.push_back(font);
8143
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
8144
0
}
8145
8146
void  ImGui::PopFont()
8147
0
{
8148
0
    ImGuiContext& g = *GImGui;
8149
0
    g.CurrentWindow->DrawList->PopTextureID();
8150
0
    g.FontStack.pop_back();
8151
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
8152
0
}
8153
8154
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
8155
25.3k
{
8156
25.3k
    ImGuiContext& g = *GImGui;
8157
25.3k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
8158
25.3k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
8159
25.3k
    if (enabled)
8160
25.3k
        item_flags |= option;
8161
0
    else
8162
0
        item_flags &= ~option;
8163
25.3k
    g.CurrentItemFlags = item_flags;
8164
25.3k
    g.ItemFlagsStack.push_back(item_flags);
8165
25.3k
}
8166
8167
void ImGui::PopItemFlag()
8168
25.3k
{
8169
25.3k
    ImGuiContext& g = *GImGui;
8170
25.3k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
8171
25.3k
    g.ItemFlagsStack.pop_back();
8172
25.3k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8173
25.3k
}
8174
8175
// BeginDisabled()/EndDisabled()
8176
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
8177
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
8178
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
8179
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
8180
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
8181
void ImGui::BeginDisabled(bool disabled)
8182
0
{
8183
0
    ImGuiContext& g = *GImGui;
8184
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8185
0
    if (!was_disabled && disabled)
8186
0
    {
8187
0
        g.DisabledAlphaBackup = g.Style.Alpha;
8188
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
8189
0
    }
8190
0
    if (was_disabled || disabled)
8191
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
8192
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags); // FIXME-OPT: can we simply skip this and use DisabledStackSize?
8193
0
    g.DisabledStackSize++;
8194
0
}
8195
8196
void ImGui::EndDisabled()
8197
0
{
8198
0
    ImGuiContext& g = *GImGui;
8199
0
    IM_ASSERT(g.DisabledStackSize > 0);
8200
0
    g.DisabledStackSize--;
8201
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
8202
    //PopItemFlag();
8203
0
    g.ItemFlagsStack.pop_back();
8204
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8205
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
8206
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
8207
0
}
8208
8209
// Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name.
8210
// Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal.
8211
// The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled().
8212
void ImGui::BeginDisabledOverrideReenable()
8213
0
{
8214
0
    ImGuiContext& g = *GImGui;
8215
0
    IM_ASSERT(g.CurrentItemFlags & ImGuiItemFlags_Disabled);
8216
0
    g.Style.Alpha = g.DisabledAlphaBackup;
8217
0
    g.CurrentItemFlags &= ~ImGuiItemFlags_Disabled;
8218
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
8219
0
    g.DisabledStackSize++;
8220
0
}
8221
8222
void ImGui::EndDisabledOverrideReenable()
8223
0
{
8224
0
    ImGuiContext& g = *GImGui;
8225
0
    g.DisabledStackSize--;
8226
0
    IM_ASSERT(g.DisabledStackSize > 0);
8227
0
    g.ItemFlagsStack.pop_back();
8228
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
8229
0
    g.Style.Alpha = g.DisabledAlphaBackup * g.Style.DisabledAlpha;
8230
0
}
8231
8232
void ImGui::PushTextWrapPos(float wrap_pos_x)
8233
0
{
8234
0
    ImGuiWindow* window = GetCurrentWindow();
8235
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
8236
0
    window->DC.TextWrapPos = wrap_pos_x;
8237
0
}
8238
8239
void ImGui::PopTextWrapPos()
8240
0
{
8241
0
    ImGuiWindow* window = GetCurrentWindow();
8242
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
8243
0
    window->DC.TextWrapPosStack.pop_back();
8244
0
}
8245
8246
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
8247
0
{
8248
0
    ImGuiWindow* last_window = NULL;
8249
0
    while (last_window != window)
8250
0
    {
8251
0
        last_window = window;
8252
0
        window = window->RootWindow;
8253
0
        if (popup_hierarchy)
8254
0
            window = window->RootWindowPopupTree;
8255
0
    if (dock_hierarchy)
8256
0
      window = window->RootWindowDockTree;
8257
0
  }
8258
0
    return window;
8259
0
}
8260
8261
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
8262
0
{
8263
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
8264
0
    if (window_root == potential_parent)
8265
0
        return true;
8266
0
    while (window != NULL)
8267
0
    {
8268
0
        if (window == potential_parent)
8269
0
            return true;
8270
0
        if (window == window_root) // end of chain
8271
0
            return false;
8272
0
        window = window->ParentWindow;
8273
0
    }
8274
0
    return false;
8275
0
}
8276
8277
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
8278
0
{
8279
0
    if (window->RootWindow == potential_parent)
8280
0
        return true;
8281
0
    while (window != NULL)
8282
0
    {
8283
0
        if (window == potential_parent)
8284
0
            return true;
8285
0
        window = window->ParentWindowInBeginStack;
8286
0
    }
8287
0
    return false;
8288
0
}
8289
8290
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
8291
0
{
8292
0
    ImGuiContext& g = *GImGui;
8293
8294
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
8295
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
8296
0
    if (display_layer_delta != 0)
8297
0
        return display_layer_delta > 0;
8298
8299
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
8300
0
    {
8301
0
        ImGuiWindow* candidate_window = g.Windows[i];
8302
0
        if (candidate_window == potential_above)
8303
0
            return true;
8304
0
        if (candidate_window == potential_below)
8305
0
            return false;
8306
0
    }
8307
0
    return false;
8308
0
}
8309
8310
// Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags_ for options.
8311
// IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app,
8312
// you should not use this function! Use the 'io.WantCaptureMouse' boolean for that!
8313
// Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details.
8314
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
8315
37.5k
{
8316
37.5k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
8317
8318
37.5k
    ImGuiContext& g = *GImGui;
8319
37.5k
    ImGuiWindow* ref_window = g.HoveredWindow;
8320
37.5k
    ImGuiWindow* cur_window = g.CurrentWindow;
8321
37.5k
    if (ref_window == NULL)
8322
24.5k
        return false;
8323
8324
13.0k
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
8325
13.0k
    {
8326
13.0k
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
8327
13.0k
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
8328
13.0k
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
8329
13.0k
        if (flags & ImGuiHoveredFlags_RootWindow)
8330
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8331
8332
13.0k
        bool result;
8333
13.0k
        if (flags & ImGuiHoveredFlags_ChildWindows)
8334
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8335
13.0k
        else
8336
13.0k
            result = (ref_window == cur_window);
8337
13.0k
        if (!result)
8338
12.9k
            return false;
8339
13.0k
    }
8340
8341
107
    if (!IsWindowContentHoverable(ref_window, flags))
8342
0
        return false;
8343
107
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
8344
107
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
8345
0
            return false;
8346
8347
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
8348
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
8349
    // to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true
8350
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
8351
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
8352
107
    if (flags & ImGuiHoveredFlags_ForTooltip)
8353
0
        flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse);
8354
107
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
8355
0
        return false;
8356
8357
107
    return true;
8358
107
}
8359
8360
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
8361
50.5k
{
8362
50.5k
    ImGuiContext& g = *GImGui;
8363
50.5k
    ImGuiWindow* ref_window = g.NavWindow;
8364
50.5k
    ImGuiWindow* cur_window = g.CurrentWindow;
8365
8366
50.5k
    if (ref_window == NULL)
8367
16.6k
        return false;
8368
33.9k
    if (flags & ImGuiFocusedFlags_AnyWindow)
8369
0
        return true;
8370
8371
33.9k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
8372
33.9k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
8373
33.9k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
8374
33.9k
    if (flags & ImGuiHoveredFlags_RootWindow)
8375
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
8376
8377
33.9k
    if (flags & ImGuiHoveredFlags_ChildWindows)
8378
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
8379
33.9k
    else
8380
33.9k
        return (ref_window == cur_window);
8381
33.9k
}
8382
8383
ImGuiID ImGui::GetWindowDockID()
8384
0
{
8385
0
    ImGuiContext& g = *GImGui;
8386
0
    return g.CurrentWindow->DockId;
8387
0
}
8388
8389
bool ImGui::IsWindowDocked()
8390
0
{
8391
0
    ImGuiContext& g = *GImGui;
8392
0
    return g.CurrentWindow->DockIsActive;
8393
0
}
8394
8395
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
8396
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
8397
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
8398
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
8399
0
{
8400
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
8401
0
}
8402
8403
float ImGui::GetWindowWidth()
8404
6.31k
{
8405
6.31k
    ImGuiWindow* window = GImGui->CurrentWindow;
8406
6.31k
    return window->Size.x;
8407
6.31k
}
8408
8409
float ImGui::GetWindowHeight()
8410
6.35k
{
8411
6.35k
    ImGuiWindow* window = GImGui->CurrentWindow;
8412
6.35k
    return window->Size.y;
8413
6.35k
}
8414
8415
ImVec2 ImGui::GetWindowPos()
8416
0
{
8417
0
    ImGuiContext& g = *GImGui;
8418
0
    ImGuiWindow* window = g.CurrentWindow;
8419
0
    return window->Pos;
8420
0
}
8421
8422
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
8423
126
{
8424
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8425
126
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
8426
0
        return;
8427
8428
126
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8429
126
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8430
126
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
8431
8432
    // Set
8433
126
    const ImVec2 old_pos = window->Pos;
8434
126
    window->Pos = ImTrunc(pos);
8435
126
    ImVec2 offset = window->Pos - old_pos;
8436
126
    if (offset.x == 0.0f && offset.y == 0.0f)
8437
0
        return;
8438
126
    MarkIniSettingsDirty(window);
8439
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
8440
126
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
8441
126
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
8442
126
    window->DC.IdealMaxPos += offset;
8443
126
    window->DC.CursorStartPos += offset;
8444
126
}
8445
8446
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
8447
0
{
8448
0
    ImGuiWindow* window = GetCurrentWindowRead();
8449
0
    SetWindowPos(window, pos, cond);
8450
0
}
8451
8452
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
8453
0
{
8454
0
    if (ImGuiWindow* window = FindWindowByName(name))
8455
0
        SetWindowPos(window, pos, cond);
8456
0
}
8457
8458
ImVec2 ImGui::GetWindowSize()
8459
0
{
8460
0
    ImGuiWindow* window = GetCurrentWindowRead();
8461
0
    return window->Size;
8462
0
}
8463
8464
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
8465
105k
{
8466
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8467
105k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8468
80.5k
        return;
8469
8470
25.3k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8471
25.3k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8472
8473
    // Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags_AlwaysAutoResize)
8474
25.3k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8475
11
        window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8476
25.3k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) == 0 || window->Appearing || (window->ChildFlags & ImGuiChildFlags_AlwaysAutoResize) != 0)
8477
11
        window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8478
8479
    // Set
8480
25.3k
    ImVec2 old_size = window->SizeFull;
8481
25.3k
    if (size.x <= 0.0f)
8482
0
        window->AutoFitOnlyGrows = false;
8483
25.3k
    else
8484
25.3k
        window->SizeFull.x = IM_TRUNC(size.x);
8485
25.3k
    if (size.y <= 0.0f)
8486
0
        window->AutoFitOnlyGrows = false;
8487
25.3k
    else
8488
25.3k
        window->SizeFull.y = IM_TRUNC(size.y);
8489
25.3k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8490
25.1k
        MarkIniSettingsDirty(window);
8491
25.3k
}
8492
8493
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8494
0
{
8495
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8496
0
}
8497
8498
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8499
0
{
8500
0
    if (ImGuiWindow* window = FindWindowByName(name))
8501
0
        SetWindowSize(window, size, cond);
8502
0
}
8503
8504
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8505
0
{
8506
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8507
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8508
0
        return;
8509
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8510
8511
    // Set
8512
0
    window->Collapsed = collapsed;
8513
0
}
8514
8515
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8516
0
{
8517
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8518
0
    window->HitTestHoleSize = ImVec2ih(size);
8519
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8520
0
}
8521
8522
void ImGui::SetWindowHiddenAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8523
0
{
8524
0
    window->Hidden = window->SkipItems = true;
8525
0
    window->HiddenFramesCanSkipItems = 1;
8526
0
}
8527
8528
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8529
0
{
8530
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8531
0
}
8532
8533
bool ImGui::IsWindowCollapsed()
8534
0
{
8535
0
    ImGuiWindow* window = GetCurrentWindowRead();
8536
0
    return window->Collapsed;
8537
0
}
8538
8539
bool ImGui::IsWindowAppearing()
8540
0
{
8541
0
    ImGuiWindow* window = GetCurrentWindowRead();
8542
0
    return window->Appearing;
8543
0
}
8544
8545
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8546
0
{
8547
0
    if (ImGuiWindow* window = FindWindowByName(name))
8548
0
        SetWindowCollapsed(window, collapsed, cond);
8549
0
}
8550
8551
void ImGui::SetWindowFocus()
8552
6.31k
{
8553
6.31k
    FocusWindow(GImGui->CurrentWindow);
8554
6.31k
}
8555
8556
void ImGui::SetWindowFocus(const char* name)
8557
0
{
8558
0
    if (name)
8559
0
    {
8560
0
        if (ImGuiWindow* window = FindWindowByName(name))
8561
0
            FocusWindow(window);
8562
0
    }
8563
0
    else
8564
0
    {
8565
0
        FocusWindow(NULL);
8566
0
    }
8567
0
}
8568
8569
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8570
0
{
8571
0
    ImGuiContext& g = *GImGui;
8572
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8573
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8574
0
    g.NextWindowData.PosVal = pos;
8575
0
    g.NextWindowData.PosPivotVal = pivot;
8576
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8577
0
    g.NextWindowData.PosUndock = true;
8578
0
}
8579
8580
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8581
105k
{
8582
105k
    ImGuiContext& g = *GImGui;
8583
105k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8584
105k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8585
105k
    g.NextWindowData.SizeVal = size;
8586
105k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8587
105k
}
8588
8589
// For each axis:
8590
// - Use 0.0f as min or FLT_MAX as max if you don't want limits, e.g. size_min = (500.0f, 0.0f), size_max = (FLT_MAX, FLT_MAX) sets a minimum width.
8591
// - Use -1 for both min and max of same axis to preserve current size which itself is a constraint.
8592
// - See "Demo->Examples->Constrained-resizing window" for examples.
8593
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8594
0
{
8595
0
    ImGuiContext& g = *GImGui;
8596
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8597
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8598
0
    g.NextWindowData.SizeCallback = custom_callback;
8599
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8600
0
}
8601
8602
// Content size = inner scrollable rectangle, padded with WindowPadding.
8603
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8604
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8605
0
{
8606
0
    ImGuiContext& g = *GImGui;
8607
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8608
0
    g.NextWindowData.ContentSizeVal = ImTrunc(size);
8609
0
}
8610
8611
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8612
0
{
8613
0
    ImGuiContext& g = *GImGui;
8614
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8615
0
    g.NextWindowData.ScrollVal = scroll;
8616
0
}
8617
8618
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8619
0
{
8620
0
    ImGuiContext& g = *GImGui;
8621
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8622
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8623
0
    g.NextWindowData.CollapsedVal = collapsed;
8624
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8625
0
}
8626
8627
void ImGui::SetNextWindowFocus()
8628
0
{
8629
0
    ImGuiContext& g = *GImGui;
8630
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8631
0
}
8632
8633
void ImGui::SetNextWindowBgAlpha(float alpha)
8634
0
{
8635
0
    ImGuiContext& g = *GImGui;
8636
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8637
0
    g.NextWindowData.BgAlphaVal = alpha;
8638
0
}
8639
8640
void ImGui::SetNextWindowViewport(ImGuiID id)
8641
0
{
8642
0
    ImGuiContext& g = *GImGui;
8643
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8644
0
    g.NextWindowData.ViewportId = id;
8645
0
}
8646
8647
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8648
0
{
8649
0
    ImGuiContext& g = *GImGui;
8650
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8651
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8652
0
    g.NextWindowData.DockId = id;
8653
0
}
8654
8655
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8656
0
{
8657
0
    ImGuiContext& g = *GImGui;
8658
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8659
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8660
0
    g.NextWindowData.WindowClass = *window_class;
8661
0
}
8662
8663
// This is experimental and meant to be a toy for exploring a future/wider range of features.
8664
void ImGui::SetNextWindowRefreshPolicy(ImGuiWindowRefreshFlags flags)
8665
0
{
8666
0
    ImGuiContext& g = *GImGui;
8667
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasRefreshPolicy;
8668
0
    g.NextWindowData.RefreshFlagsVal = flags;
8669
0
}
8670
8671
ImDrawList* ImGui::GetWindowDrawList()
8672
25.3k
{
8673
25.3k
    ImGuiWindow* window = GetCurrentWindow();
8674
25.3k
    return window->DrawList;
8675
25.3k
}
8676
8677
float ImGui::GetWindowDpiScale()
8678
0
{
8679
0
    ImGuiContext& g = *GImGui;
8680
0
    return g.CurrentDpiScale;
8681
0
}
8682
8683
ImGuiViewport* ImGui::GetWindowViewport()
8684
0
{
8685
0
    ImGuiContext& g = *GImGui;
8686
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8687
0
    return g.CurrentViewport;
8688
0
}
8689
8690
ImFont* ImGui::GetFont()
8691
1.33M
{
8692
1.33M
    return GImGui->Font;
8693
1.33M
}
8694
8695
float ImGui::GetFontSize()
8696
1.33M
{
8697
1.33M
    return GImGui->FontSize;
8698
1.33M
}
8699
8700
ImVec2 ImGui::GetFontTexUvWhitePixel()
8701
0
{
8702
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8703
0
}
8704
8705
void ImGui::SetWindowFontScale(float scale)
8706
0
{
8707
0
    IM_ASSERT(scale > 0.0f);
8708
0
    ImGuiContext& g = *GImGui;
8709
0
    ImGuiWindow* window = GetCurrentWindow();
8710
0
    window->FontWindowScale = scale;
8711
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8712
0
    g.FontScale = g.DrawListSharedData.FontScale = g.FontSize / g.Font->FontSize;
8713
0
}
8714
8715
void ImGui::PushFocusScope(ImGuiID id)
8716
186k
{
8717
186k
    ImGuiContext& g = *GImGui;
8718
186k
    ImGuiFocusScopeData data;
8719
186k
    data.ID = id;
8720
186k
    data.WindowID = g.CurrentWindow->ID;
8721
186k
    g.FocusScopeStack.push_back(data);
8722
186k
    g.CurrentFocusScopeId = id;
8723
186k
}
8724
8725
void ImGui::PopFocusScope()
8726
186k
{
8727
186k
    ImGuiContext& g = *GImGui;
8728
186k
    if (g.FocusScopeStack.Size == 0)
8729
0
    {
8730
0
        IM_ASSERT_USER_ERROR(g.FocusScopeStack.Size > 0, "Calling PopFocusScope() too many times!");
8731
0
        return;
8732
0
    }
8733
186k
    g.FocusScopeStack.pop_back();
8734
186k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back().ID : 0;
8735
186k
}
8736
8737
void ImGui::SetNavFocusScope(ImGuiID focus_scope_id)
8738
7.94k
{
8739
7.94k
    ImGuiContext& g = *GImGui;
8740
7.94k
    g.NavFocusScopeId = focus_scope_id;
8741
7.94k
    g.NavFocusRoute.resize(0); // Invalidate
8742
7.94k
    if (focus_scope_id == 0)
8743
2.65k
        return;
8744
5.29k
    IM_ASSERT(g.NavWindow != NULL);
8745
8746
    // Store current path (in reverse order)
8747
5.29k
    if (focus_scope_id == g.CurrentFocusScopeId)
8748
3.86k
    {
8749
        // Top of focus stack contains local focus scopes inside current window
8750
7.72k
        for (int n = g.FocusScopeStack.Size - 1; n >= 0 && g.FocusScopeStack.Data[n].WindowID == g.CurrentWindow->ID; n--)
8751
3.86k
            g.NavFocusRoute.push_back(g.FocusScopeStack.Data[n]);
8752
3.86k
    }
8753
1.43k
    else if (focus_scope_id == g.NavWindow->NavRootFocusScopeId)
8754
1.40k
        g.NavFocusRoute.push_back({ focus_scope_id, g.NavWindow->ID });
8755
25
    else
8756
25
        return;
8757
8758
    // Then follow on manually set ParentWindowForFocusRoute field (#6798)
8759
8.28k
    for (ImGuiWindow* window = g.NavWindow->ParentWindowForFocusRoute; window != NULL; window = window->ParentWindowForFocusRoute)
8760
3.01k
        g.NavFocusRoute.push_back({ window->NavRootFocusScopeId, window->ID });
8761
5.26k
    IM_ASSERT(g.NavFocusRoute.Size < 100); // Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3
8762
5.26k
}
8763
8764
// Focus = move navigation cursor, set scrolling, set focus window.
8765
void ImGui::FocusItem()
8766
0
{
8767
0
    ImGuiContext& g = *GImGui;
8768
0
    ImGuiWindow* window = g.CurrentWindow;
8769
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8770
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8771
0
    {
8772
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8773
0
        return;
8774
0
    }
8775
8776
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight | ImGuiNavMoveFlags_NoSelect;
8777
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8778
0
    SetNavWindow(window);
8779
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8780
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8781
0
}
8782
8783
void ImGui::ActivateItemByID(ImGuiID id)
8784
0
{
8785
0
    ImGuiContext& g = *GImGui;
8786
0
    g.NavNextActivateId = id;
8787
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8788
0
}
8789
8790
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8791
// But ActivateItem() should function without altering scroll/focus?
8792
void ImGui::SetKeyboardFocusHere(int offset)
8793
0
{
8794
0
    ImGuiContext& g = *GImGui;
8795
0
    ImGuiWindow* window = g.CurrentWindow;
8796
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8797
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8798
8799
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8800
    // When we refactor this function into ActivateItem() we may want to make this an option.
8801
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8802
    // is also automatically dropped in the event g.ActiveId is stolen.
8803
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8804
0
    {
8805
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8806
0
        return;
8807
0
    }
8808
8809
0
    SetNavWindow(window);
8810
8811
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSetNavHighlight;
8812
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8813
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8814
0
    if (offset == -1)
8815
0
    {
8816
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8817
0
    }
8818
0
    else
8819
0
    {
8820
0
        g.NavTabbingDir = 1;
8821
0
        g.NavTabbingCounter = offset + 1;
8822
0
    }
8823
0
}
8824
8825
void ImGui::SetItemDefaultFocus()
8826
0
{
8827
0
    ImGuiContext& g = *GImGui;
8828
0
    ImGuiWindow* window = g.CurrentWindow;
8829
0
    if (!window->Appearing)
8830
0
        return;
8831
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8832
0
        return;
8833
8834
0
    g.NavInitRequest = false;
8835
0
    NavApplyItemToResult(&g.NavInitResult);
8836
0
    NavUpdateAnyRequestFlag();
8837
8838
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8839
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8840
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8841
0
}
8842
8843
void ImGui::SetStateStorage(ImGuiStorage* tree)
8844
0
{
8845
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8846
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8847
0
}
8848
8849
ImGuiStorage* ImGui::GetStateStorage()
8850
0
{
8851
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8852
0
    return window->DC.StateStorage;
8853
0
}
8854
8855
bool ImGui::IsRectVisible(const ImVec2& size)
8856
0
{
8857
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8858
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8859
0
}
8860
8861
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8862
0
{
8863
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8864
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8865
0
}
8866
8867
//-----------------------------------------------------------------------------
8868
// [SECTION] ID STACK
8869
//-----------------------------------------------------------------------------
8870
8871
// This is one of the very rare legacy case where we use ImGuiWindow methods,
8872
// it should ideally be flattened at some point but it's been used a lots by widgets.
8873
IM_MSVC_RUNTIME_CHECKS_OFF
8874
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
8875
258k
{
8876
258k
    ImGuiID seed = IDStack.back();
8877
258k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8878
258k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8879
258k
    ImGuiContext& g = *Ctx;
8880
258k
    if (g.DebugHookIdInfo == id)
8881
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8882
258k
#endif
8883
258k
    return id;
8884
258k
}
8885
8886
ImGuiID ImGuiWindow::GetID(const void* ptr)
8887
0
{
8888
0
    ImGuiID seed = IDStack.back();
8889
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
8890
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8891
0
    ImGuiContext& g = *Ctx;
8892
0
    if (g.DebugHookIdInfo == id)
8893
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
8894
0
#endif
8895
0
    return id;
8896
0
}
8897
8898
ImGuiID ImGuiWindow::GetID(int n)
8899
152k
{
8900
152k
    ImGuiID seed = IDStack.back();
8901
152k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8902
152k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8903
152k
    ImGuiContext& g = *Ctx;
8904
152k
    if (g.DebugHookIdInfo == id)
8905
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8906
152k
#endif
8907
152k
    return id;
8908
152k
}
8909
8910
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
8911
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
8912
0
{
8913
0
    ImGuiID seed = IDStack.back();
8914
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
8915
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
8916
0
    return id;
8917
0
}
8918
8919
void ImGui::PushID(const char* str_id)
8920
25.3k
{
8921
25.3k
    ImGuiContext& g = *GImGui;
8922
25.3k
    ImGuiWindow* window = g.CurrentWindow;
8923
25.3k
    ImGuiID id = window->GetID(str_id);
8924
25.3k
    window->IDStack.push_back(id);
8925
25.3k
}
8926
8927
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8928
0
{
8929
0
    ImGuiContext& g = *GImGui;
8930
0
    ImGuiWindow* window = g.CurrentWindow;
8931
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8932
0
    window->IDStack.push_back(id);
8933
0
}
8934
8935
void ImGui::PushID(const void* ptr_id)
8936
0
{
8937
0
    ImGuiContext& g = *GImGui;
8938
0
    ImGuiWindow* window = g.CurrentWindow;
8939
0
    ImGuiID id = window->GetID(ptr_id);
8940
0
    window->IDStack.push_back(id);
8941
0
}
8942
8943
void ImGui::PushID(int int_id)
8944
0
{
8945
0
    ImGuiContext& g = *GImGui;
8946
0
    ImGuiWindow* window = g.CurrentWindow;
8947
0
    ImGuiID id = window->GetID(int_id);
8948
0
    window->IDStack.push_back(id);
8949
0
}
8950
8951
// Push a given id value ignoring the ID stack as a seed.
8952
void ImGui::PushOverrideID(ImGuiID id)
8953
0
{
8954
0
    ImGuiContext& g = *GImGui;
8955
0
    ImGuiWindow* window = g.CurrentWindow;
8956
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8957
0
    if (g.DebugHookIdInfo == id)
8958
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8959
0
#endif
8960
0
    window->IDStack.push_back(id);
8961
0
}
8962
8963
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8964
// (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level.
8965
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8966
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8967
0
{
8968
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8969
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8970
0
    ImGuiContext& g = *GImGui;
8971
0
    if (g.DebugHookIdInfo == id)
8972
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8973
0
#endif
8974
0
    return id;
8975
0
}
8976
8977
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8978
0
{
8979
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8980
0
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
8981
0
    ImGuiContext& g = *GImGui;
8982
0
    if (g.DebugHookIdInfo == id)
8983
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8984
0
#endif
8985
0
    return id;
8986
0
}
8987
8988
void ImGui::PopID()
8989
25.3k
{
8990
25.3k
    ImGuiWindow* window = GImGui->CurrentWindow;
8991
25.3k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8992
25.3k
    window->IDStack.pop_back();
8993
25.3k
}
8994
8995
ImGuiID ImGui::GetID(const char* str_id)
8996
0
{
8997
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8998
0
    return window->GetID(str_id);
8999
0
}
9000
9001
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
9002
0
{
9003
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9004
0
    return window->GetID(str_id_begin, str_id_end);
9005
0
}
9006
9007
ImGuiID ImGui::GetID(const void* ptr_id)
9008
0
{
9009
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9010
0
    return window->GetID(ptr_id);
9011
0
}
9012
9013
ImGuiID ImGui::GetID(int int_id)
9014
0
{
9015
0
    ImGuiWindow* window = GImGui->CurrentWindow;
9016
0
    return window->GetID(int_id);
9017
0
}
9018
IM_MSVC_RUNTIME_CHECKS_RESTORE
9019
9020
//-----------------------------------------------------------------------------
9021
// [SECTION] INPUTS
9022
//-----------------------------------------------------------------------------
9023
// - GetModForModKey() [Internal]
9024
// - FixupKeyChord() [Internal]
9025
// - GetKeyData() [Internal]
9026
// - GetKeyIndex() [Internal]
9027
// - GetKeyName()
9028
// - GetKeyChordName() [Internal]
9029
// - CalcTypematicRepeatAmount() [Internal]
9030
// - GetTypematicRepeatRate() [Internal]
9031
// - GetKeyPressedAmount() [Internal]
9032
// - GetKeyMagnitude2d() [Internal]
9033
//-----------------------------------------------------------------------------
9034
// - UpdateKeyRoutingTable() [Internal]
9035
// - GetRoutingIdFromOwnerId() [Internal]
9036
// - GetShortcutRoutingData() [Internal]
9037
// - CalcRoutingScore() [Internal]
9038
// - SetShortcutRouting() [Internal]
9039
// - TestShortcutRouting() [Internal]
9040
//-----------------------------------------------------------------------------
9041
// - IsKeyDown()
9042
// - IsKeyPressed()
9043
// - IsKeyReleased()
9044
//-----------------------------------------------------------------------------
9045
// - IsMouseDown()
9046
// - IsMouseClicked()
9047
// - IsMouseReleased()
9048
// - IsMouseDoubleClicked()
9049
// - GetMouseClickedCount()
9050
// - IsMouseHoveringRect() [Internal]
9051
// - IsMouseDragPastThreshold() [Internal]
9052
// - IsMouseDragging()
9053
// - GetMousePos()
9054
// - SetMousePos() [Internal]
9055
// - GetMousePosOnOpeningCurrentPopup()
9056
// - IsMousePosValid()
9057
// - IsAnyMouseDown()
9058
// - GetMouseDragDelta()
9059
// - ResetMouseDragDelta()
9060
// - GetMouseCursor()
9061
// - SetMouseCursor()
9062
//-----------------------------------------------------------------------------
9063
// - UpdateAliasKey()
9064
// - GetMergedModsFromKeys()
9065
// - UpdateKeyboardInputs()
9066
// - UpdateMouseInputs()
9067
//-----------------------------------------------------------------------------
9068
// - LockWheelingWindow [Internal]
9069
// - FindBestWheelingWindow [Internal]
9070
// - UpdateMouseWheel() [Internal]
9071
//-----------------------------------------------------------------------------
9072
// - SetNextFrameWantCaptureKeyboard()
9073
// - SetNextFrameWantCaptureMouse()
9074
//-----------------------------------------------------------------------------
9075
// - GetInputSourceName() [Internal]
9076
// - DebugPrintInputEvent() [Internal]
9077
// - UpdateInputEvents() [Internal]
9078
//-----------------------------------------------------------------------------
9079
// - GetKeyOwner() [Internal]
9080
// - TestKeyOwner() [Internal]
9081
// - SetKeyOwner() [Internal]
9082
// - SetItemKeyOwner() [Internal]
9083
// - Shortcut() [Internal]
9084
//-----------------------------------------------------------------------------
9085
9086
static ImGuiKeyChord GetModForModKey(ImGuiKey key)
9087
0
{
9088
0
    if (key == ImGuiKey_LeftCtrl || key == ImGuiKey_RightCtrl)
9089
0
        return ImGuiMod_Ctrl;
9090
0
    if (key == ImGuiKey_LeftShift || key == ImGuiKey_RightShift)
9091
0
        return ImGuiMod_Shift;
9092
0
    if (key == ImGuiKey_LeftAlt || key == ImGuiKey_RightAlt)
9093
0
        return ImGuiMod_Alt;
9094
0
    if (key == ImGuiKey_LeftSuper || key == ImGuiKey_RightSuper)
9095
0
        return ImGuiMod_Super;
9096
0
    return ImGuiMod_None;
9097
0
}
9098
9099
ImGuiKeyChord ImGui::FixupKeyChord(ImGuiKeyChord key_chord)
9100
322k
{
9101
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9102
322k
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9103
322k
    if (IsModKey(key))
9104
0
        key_chord |= GetModForModKey(key);
9105
322k
    return key_chord;
9106
322k
}
9107
9108
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
9109
2.38M
{
9110
2.38M
    ImGuiContext& g = *ctx;
9111
9112
    // Special storage location for mods
9113
2.38M
    if (key & ImGuiMod_Mask_)
9114
644k
        key = ConvertSingleModFlagToKey(key);
9115
9116
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9117
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
9118
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
9119
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
9120
#else
9121
2.38M
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
9122
2.38M
#endif
9123
2.38M
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
9124
2.38M
}
9125
9126
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9127
// Formally moved to obsolete section in 1.90.5 in spite of documented as obsolete since 1.87
9128
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
9129
{
9130
    ImGuiContext& g = *GImGui;
9131
    IM_ASSERT(IsNamedKey(key));
9132
    const ImGuiKeyData* key_data = GetKeyData(key);
9133
    return (ImGuiKey)(key_data - g.IO.KeysData);
9134
}
9135
#endif
9136
9137
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
9138
static const char* const GKeyNames[] =
9139
{
9140
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
9141
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
9142
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
9143
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
9144
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
9145
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
9146
    "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24",
9147
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
9148
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
9149
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
9150
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
9151
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
9152
    "AppBack", "AppForward",
9153
    "GamepadStart", "GamepadBack",
9154
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
9155
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
9156
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
9157
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
9158
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
9159
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
9160
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
9161
};
9162
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
9163
9164
const char* ImGui::GetKeyName(ImGuiKey key)
9165
0
{
9166
0
    if (key == ImGuiKey_None)
9167
0
        return "None";
9168
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
9169
0
    IM_ASSERT(IsNamedKeyOrMod(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
9170
#else
9171
    ImGuiContext& g = *GImGui;
9172
    if (IsLegacyKey(key))
9173
    {
9174
        if (g.IO.KeyMap[key] == -1)
9175
            return "N/A";
9176
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
9177
        key = (ImGuiKey)g.IO.KeyMap[key];
9178
    }
9179
#endif
9180
0
    if (key & ImGuiMod_Mask_)
9181
0
        key = ConvertSingleModFlagToKey(key);
9182
0
    if (!IsNamedKey(key))
9183
0
        return "Unknown";
9184
9185
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
9186
0
}
9187
9188
// Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super.
9189
// Lifetime of return value: valid until next call to same function.
9190
const char* ImGui::GetKeyChordName(ImGuiKeyChord key_chord)
9191
0
{
9192
0
    ImGuiContext& g = *GImGui;
9193
9194
0
    const ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9195
0
    if (IsModKey(key))
9196
0
        key_chord &= ~GetModForModKey(key); // Return "Ctrl+LeftShift" instead of "Ctrl+Shift+LeftShift"
9197
0
    ImFormatString(g.TempKeychordName, IM_ARRAYSIZE(g.TempKeychordName), "%s%s%s%s%s",
9198
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
9199
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
9200
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
9201
0
        (key_chord & ImGuiMod_Super) ? "Super+" : "",
9202
0
        (key != ImGuiKey_None || key_chord == ImGuiKey_None) ? GetKeyName(key) : "");
9203
0
    size_t len;
9204
0
    if (key == ImGuiKey_None && key_chord != 0)
9205
0
        if ((len = strlen(g.TempKeychordName)) != 0) // Remove trailing '+'
9206
0
            g.TempKeychordName[len - 1] = 0;
9207
0
    return g.TempKeychordName;
9208
0
}
9209
9210
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
9211
// t1 = current time (e.g.: g.Time)
9212
// An event is triggered at:
9213
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
9214
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
9215
4.29k
{
9216
4.29k
    if (t1 == 0.0f)
9217
0
        return 1;
9218
4.29k
    if (t0 >= t1)
9219
0
        return 0;
9220
4.29k
    if (repeat_rate <= 0.0f)
9221
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
9222
4.29k
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
9223
4.29k
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
9224
4.29k
    const int count = count_t1 - count_t0;
9225
4.29k
    return count;
9226
4.29k
}
9227
9228
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
9229
10.5k
{
9230
10.5k
    ImGuiContext& g = *GImGui;
9231
10.5k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
9232
10.5k
    {
9233
736
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
9234
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
9235
9.79k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
9236
10.5k
    }
9237
10.5k
}
9238
9239
// Return value representing the number of presses in the last time period, for the given repeat rate
9240
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
9241
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
9242
4.29k
{
9243
4.29k
    ImGuiContext& g = *GImGui;
9244
4.29k
    const ImGuiKeyData* key_data = GetKeyData(key);
9245
4.29k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9246
0
        return 0;
9247
4.29k
    const float t = key_data->DownDuration;
9248
4.29k
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
9249
4.29k
}
9250
9251
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
9252
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
9253
0
{
9254
0
    return ImVec2(
9255
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
9256
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
9257
0
}
9258
9259
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
9260
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
9261
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
9262
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
9263
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
9264
80.5k
{
9265
80.5k
    ImGuiContext& g = *GImGui;
9266
80.5k
    rt->EntriesNext.resize(0);
9267
12.4M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9268
12.4M
    {
9269
12.4M
        const int new_routing_start_idx = rt->EntriesNext.Size;
9270
12.4M
        ImGuiKeyRoutingData* routing_entry;
9271
12.4M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
9272
0
        {
9273
0
            routing_entry = &rt->Entries[old_routing_idx];
9274
0
            routing_entry->RoutingCurrScore = routing_entry->RoutingNextScore;
9275
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
9276
0
            routing_entry->RoutingNext = ImGuiKeyOwner_NoOwner;
9277
0
            routing_entry->RoutingNextScore = 255;
9278
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_NoOwner)
9279
0
                continue;
9280
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
9281
9282
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
9283
            // This is the result of previous frame's SetShortcutRouting() call.
9284
0
            if (routing_entry->Mods == g.IO.KeyMods)
9285
0
            {
9286
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9287
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
9288
0
                {
9289
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
9290
                    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr);
9291
0
                }
9292
0
            }
9293
0
        }
9294
9295
        // Rewrite linked-list
9296
12.4M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
9297
12.4M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
9298
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
9299
12.4M
    }
9300
80.5k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
9301
80.5k
}
9302
9303
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
9304
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
9305
0
{
9306
0
    ImGuiContext& g = *GImGui;
9307
0
    return (owner_id != ImGuiKeyOwner_NoOwner && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
9308
0
}
9309
9310
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
9311
0
{
9312
    // Majority of shortcuts will be Key + any number of Mods
9313
    // We accept _Single_ mod with ImGuiKey_None.
9314
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
9315
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
9316
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
9317
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
9318
0
    ImGuiContext& g = *GImGui;
9319
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
9320
0
    ImGuiKeyRoutingData* routing_data;
9321
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9322
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9323
0
    if (key == ImGuiKey_None)
9324
0
        key = ConvertSingleModFlagToKey(mods);
9325
0
    IM_ASSERT(IsNamedKey(key));
9326
9327
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
9328
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
9329
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
9330
0
    {
9331
0
        routing_data = &rt->Entries[idx];
9332
0
        if (routing_data->Mods == mods)
9333
0
            return routing_data;
9334
0
    }
9335
9336
    // Add to linked-list
9337
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
9338
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
9339
0
    routing_data = &rt->Entries[routing_data_idx];
9340
0
    routing_data->Mods = (ImU16)mods;
9341
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
9342
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
9343
0
    return routing_data;
9344
0
}
9345
9346
// Current score encoding (lower is highest priority):
9347
//  -   0: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverActive
9348
//  -   1: ImGuiInputFlags_ActiveItem or ImGuiInputFlags_RouteFocused (if item active)
9349
//  -   2: ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused
9350
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
9351
//  - 254: ImGuiInputFlags_RouteGlobal
9352
//  - 255: never route
9353
// 'flags' should include an explicit routing policy
9354
static int CalcRoutingScore(ImGuiID focus_scope_id, ImGuiID owner_id, ImGuiInputFlags flags)
9355
0
{
9356
0
    ImGuiContext& g = *GImGui;
9357
0
    if (flags & ImGuiInputFlags_RouteFocused)
9358
0
    {
9359
        // ActiveID gets top priority
9360
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
9361
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9362
0
            return 1;
9363
9364
        // Score based on distance to focused window (lower is better)
9365
        // Assuming both windows are submitting a routing request,
9366
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
9367
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
9368
        // Assuming only WindowA is submitting a routing request,
9369
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
9370
        // This essentially follow the window->ParentWindowForFocusRoute chain.
9371
0
        if (focus_scope_id == 0)
9372
0
            return 255;
9373
0
        for (int index_in_focus_path = 0; index_in_focus_path < g.NavFocusRoute.Size; index_in_focus_path++)
9374
0
            if (g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id)
9375
0
                return 3 + index_in_focus_path;
9376
0
        return 255;
9377
0
    }
9378
0
    else if (flags & ImGuiInputFlags_RouteActive)
9379
0
    {
9380
0
        if (owner_id != 0 && g.ActiveId == owner_id)
9381
0
            return 1;
9382
0
        return 255;
9383
0
    }
9384
0
    else if (flags & ImGuiInputFlags_RouteGlobal)
9385
0
    {
9386
0
        if (flags & ImGuiInputFlags_RouteOverActive)
9387
0
            return 0;
9388
0
        if (flags & ImGuiInputFlags_RouteOverFocused)
9389
0
            return 2;
9390
0
        return 254;
9391
0
    }
9392
0
    IM_ASSERT(0);
9393
0
    return 0;
9394
0
}
9395
9396
// We need this to filter some Shortcut() routes when an item e.g. an InputText() is active
9397
// e.g. ImGuiKey_G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey_G can be.
9398
static bool IsKeyChordPotentiallyCharInput(ImGuiKeyChord key_chord)
9399
0
{
9400
    // Mimic 'ignore_char_inputs' logic in InputText()
9401
0
    ImGuiContext& g = *GImGui;
9402
9403
    // When the right mods are pressed it cannot be a char input so we won't filter the shortcut out.
9404
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9405
0
    const bool ignore_char_inputs = ((mods & ImGuiMod_Ctrl) && !(mods & ImGuiMod_Alt)) || (g.IO.ConfigMacOSXBehaviors && (mods & ImGuiMod_Ctrl));
9406
0
    if (ignore_char_inputs)
9407
0
        return false;
9408
9409
    // Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered.
9410
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9411
0
    return g.KeysMayBeCharInput.TestBit(key);
9412
0
}
9413
9414
// Request a desired route for an input chord (key + mods).
9415
// Return true if the route is available this frame.
9416
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
9417
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
9418
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
9419
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
9420
161k
{
9421
161k
    ImGuiContext& g = *GImGui;
9422
161k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
9423
0
        flags |= ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
9424
161k
    else
9425
161k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteTypeMask_)); // Check that only 1 routing flag is used
9426
161k
    IM_ASSERT(owner_id != ImGuiKeyOwner_Any && owner_id != ImGuiKeyOwner_NoOwner);
9427
161k
    if (flags & (ImGuiInputFlags_RouteOverFocused | ImGuiInputFlags_RouteOverActive | ImGuiInputFlags_RouteUnlessBgFocused))
9428
161k
        IM_ASSERT(flags & ImGuiInputFlags_RouteGlobal);
9429
9430
    // Add ImGuiMod_XXXX when a corresponding ImGuiKey_LeftXXX/ImGuiKey_RightXXX is specified.
9431
161k
    key_chord = FixupKeyChord(key_chord);
9432
9433
    // [DEBUG] Debug break requested by user
9434
161k
    if (g.DebugBreakInShortcutRouting == key_chord)
9435
0
        IM_DEBUG_BREAK();
9436
9437
161k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
9438
0
        if (g.NavWindow == NULL)
9439
0
            return false;
9440
9441
    // Note how ImGuiInputFlags_RouteAlways won't set routing and thus won't set owner. May want to rework this?
9442
161k
    if (flags & ImGuiInputFlags_RouteAlways)
9443
161k
    {
9444
161k
        IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register\n", GetKeyChordName(key_chord), flags, owner_id);
9445
161k
        return true;
9446
161k
    }
9447
9448
    // Specific culling when there's an active item.
9449
0
    if (g.ActiveId != 0 && g.ActiveId != owner_id)
9450
0
    {
9451
0
        if (flags & ImGuiInputFlags_RouteActive)
9452
0
            return false;
9453
9454
        // Cull shortcuts with no modifiers when it could generate a character.
9455
        // e.g. Shortcut(ImGuiKey_G) also generates 'g' character, should not trigger when InputText() is active.
9456
        // but  Shortcut(Ctrl+G) should generally trigger when InputText() is active.
9457
        // TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active.
9458
        // (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined)
9459
0
        if (g.IO.WantTextInput && IsKeyChordPotentiallyCharInput(key_chord))
9460
0
        {
9461
0
            IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input\n", GetKeyChordName(key_chord), flags, owner_id);
9462
0
            return false;
9463
0
        }
9464
9465
        // ActiveIdUsingAllKeyboardKeys trumps all for ActiveId
9466
0
        if ((flags & ImGuiInputFlags_RouteOverActive) == 0 && g.ActiveIdUsingAllKeyboardKeys)
9467
0
        {
9468
0
            ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9469
0
            if (key == ImGuiKey_None)
9470
0
                key = ConvertSingleModFlagToKey((ImGuiKey)(key_chord & ImGuiMod_Mask_));
9471
0
            if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9472
0
                return false;
9473
0
        }
9474
0
    }
9475
9476
    // Where do we evaluate route for?
9477
0
    ImGuiID focus_scope_id = g.CurrentFocusScopeId;
9478
0
    if (flags & ImGuiInputFlags_RouteFromRootWindow)
9479
0
        focus_scope_id = g.CurrentWindow->RootWindow->ID; // See PushFocusScope() call in Begin()
9480
9481
0
    const int score = CalcRoutingScore(focus_scope_id, owner_id, flags);
9482
0
    IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> score %d\n", GetKeyChordName(key_chord), flags, owner_id, score);
9483
0
    if (score == 255)
9484
0
        return false;
9485
9486
    // Submit routing for NEXT frame (assuming score is sufficient)
9487
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
9488
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
9489
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
9490
0
    if (score < routing_data->RoutingNextScore)
9491
0
    {
9492
0
        routing_data->RoutingNext = owner_id;
9493
0
        routing_data->RoutingNextScore = (ImU8)score;
9494
0
    }
9495
9496
    // Return routing state for CURRENT frame
9497
0
    if (routing_data->RoutingCurr == owner_id)
9498
0
        IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route\n");
9499
0
    return routing_data->RoutingCurr == owner_id;
9500
0
}
9501
9502
// Currently unused by core (but used by tests)
9503
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
9504
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
9505
0
{
9506
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
9507
0
    key_chord = FixupKeyChord(key_chord);
9508
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
9509
0
    return routing_data->RoutingCurr == routing_id;
9510
0
}
9511
9512
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
9513
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
9514
bool ImGui::IsKeyDown(ImGuiKey key)
9515
1.21M
{
9516
1.21M
    return IsKeyDown(key, ImGuiKeyOwner_Any);
9517
1.21M
}
9518
9519
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
9520
1.27M
{
9521
1.27M
    const ImGuiKeyData* key_data = GetKeyData(key);
9522
1.27M
    if (!key_data->Down)
9523
1.26M
        return false;
9524
15.5k
    if (!TestKeyOwner(key, owner_id))
9525
202
        return false;
9526
15.3k
    return true;
9527
15.5k
}
9528
9529
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
9530
169k
{
9531
169k
    return IsKeyPressed(key, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9532
169k
}
9533
9534
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
9535
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiInputFlags flags, ImGuiID owner_id)
9536
514k
{
9537
514k
    const ImGuiKeyData* key_data = GetKeyData(key);
9538
514k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9539
497k
        return false;
9540
17.3k
    const float t = key_data->DownDuration;
9541
17.3k
    if (t < 0.0f)
9542
0
        return false;
9543
17.3k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
9544
17.3k
    if (flags & (ImGuiInputFlags_RepeatRateMask_ | ImGuiInputFlags_RepeatUntilMask_)) // Setting any _RepeatXXX option enables _Repeat
9545
758
        flags |= ImGuiInputFlags_Repeat;
9546
9547
17.3k
    bool pressed = (t == 0.0f);
9548
17.3k
    if (!pressed && (flags & ImGuiInputFlags_Repeat) != 0)
9549
10.5k
    {
9550
10.5k
        float repeat_delay, repeat_rate;
9551
10.5k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
9552
10.5k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
9553
10.5k
        if (pressed && (flags & ImGuiInputFlags_RepeatUntilMask_))
9554
0
        {
9555
            // Slightly bias 'key_pressed_time' as DownDuration is an accumulation of DeltaTime which we compare to an absolute time value.
9556
            // Ideally we'd replace DownDuration with KeyPressedTime but it would break user's code.
9557
0
            ImGuiContext& g = *GImGui;
9558
0
            double key_pressed_time = g.Time - t + 0.00001f;
9559
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChange) && (g.LastKeyModsChangeTime > key_pressed_time))
9560
0
                pressed = false;
9561
0
            if ((flags & ImGuiInputFlags_RepeatUntilKeyModsChangeFromNone) && (g.LastKeyModsChangeFromNoneTime > key_pressed_time))
9562
0
                pressed = false;
9563
0
            if ((flags & ImGuiInputFlags_RepeatUntilOtherKeyPress) && (g.LastKeyboardKeyPressTime > key_pressed_time))
9564
0
                pressed = false;
9565
0
        }
9566
10.5k
    }
9567
17.3k
    if (!pressed)
9568
12.9k
        return false;
9569
4.37k
    if (!TestKeyOwner(key, owner_id))
9570
312
        return false;
9571
4.06k
    return true;
9572
4.37k
}
9573
9574
bool ImGui::IsKeyReleased(ImGuiKey key)
9575
4.06k
{
9576
4.06k
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
9577
4.06k
}
9578
9579
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
9580
4.06k
{
9581
4.06k
    const ImGuiKeyData* key_data = GetKeyData(key);
9582
4.06k
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
9583
2.73k
        return false;
9584
1.33k
    if (!TestKeyOwner(key, owner_id))
9585
0
        return false;
9586
1.33k
    return true;
9587
1.33k
}
9588
9589
bool ImGui::IsMouseDown(ImGuiMouseButton button)
9590
33
{
9591
33
    ImGuiContext& g = *GImGui;
9592
33
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9593
33
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
9594
33
}
9595
9596
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
9597
253
{
9598
253
    ImGuiContext& g = *GImGui;
9599
253
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9600
253
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
9601
253
}
9602
9603
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
9604
73
{
9605
73
    return IsMouseClicked(button, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None, ImGuiKeyOwner_Any);
9606
73
}
9607
9608
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiInputFlags flags, ImGuiID owner_id)
9609
1.28k
{
9610
1.28k
    ImGuiContext& g = *GImGui;
9611
1.28k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9612
1.28k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
9613
668
        return false;
9614
612
    const float t = g.IO.MouseDownDuration[button];
9615
612
    if (t < 0.0f)
9616
0
        return false;
9617
612
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsMouseClicked) == 0); // Passing flags not supported by this function! // FIXME: Could support RepeatRate and RepeatUntil flags here.
9618
9619
612
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
9620
612
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
9621
612
    if (!pressed)
9622
519
        return false;
9623
9624
93
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
9625
0
        return false;
9626
9627
93
    return true;
9628
93
}
9629
9630
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
9631
0
{
9632
0
    ImGuiContext& g = *GImGui;
9633
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9634
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
9635
0
}
9636
9637
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
9638
1.20k
{
9639
1.20k
    ImGuiContext& g = *GImGui;
9640
1.20k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9641
1.20k
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
9642
1.20k
}
9643
9644
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
9645
73
{
9646
73
    ImGuiContext& g = *GImGui;
9647
73
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9648
73
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
9649
73
}
9650
9651
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button, ImGuiID owner_id)
9652
0
{
9653
0
    ImGuiContext& g = *GImGui;
9654
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9655
0
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), owner_id);
9656
0
}
9657
9658
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
9659
0
{
9660
0
    ImGuiContext& g = *GImGui;
9661
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9662
0
    return g.IO.MouseClickedCount[button];
9663
0
}
9664
9665
// Test if mouse cursor is hovering given rectangle
9666
// NB- Rectangle is clipped by our current clip setting
9667
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
9668
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
9669
571k
{
9670
571k
    ImGuiContext& g = *GImGui;
9671
9672
    // Clip
9673
571k
    ImRect rect_clipped(r_min, r_max);
9674
571k
    if (clip)
9675
385k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
9676
9677
    // Hit testing, expanded for touch input
9678
571k
    if (!rect_clipped.ContainsWithPad(g.IO.MousePos, g.Style.TouchExtraPadding))
9679
538k
        return false;
9680
33.0k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
9681
114
        return false;
9682
32.9k
    return true;
9683
33.0k
}
9684
9685
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
9686
// [Internal] This doesn't test if the button is pressed
9687
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
9688
4.76k
{
9689
4.76k
    ImGuiContext& g = *GImGui;
9690
4.76k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9691
4.76k
    if (lock_threshold < 0.0f)
9692
4.76k
        lock_threshold = g.IO.MouseDragThreshold;
9693
4.76k
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
9694
4.76k
}
9695
9696
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
9697
4.82k
{
9698
4.82k
    ImGuiContext& g = *GImGui;
9699
4.82k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9700
4.82k
    if (!g.IO.MouseDown[button])
9701
63
        return false;
9702
4.76k
    return IsMouseDragPastThreshold(button, lock_threshold);
9703
4.82k
}
9704
9705
ImVec2 ImGui::GetMousePos()
9706
22.1k
{
9707
22.1k
    ImGuiContext& g = *GImGui;
9708
22.1k
    return g.IO.MousePos;
9709
22.1k
}
9710
9711
// This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well.
9712
// It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) is set and supported by backend.
9713
void ImGui::TeleportMousePos(const ImVec2& pos)
9714
0
{
9715
0
    ImGuiContext& g = *GImGui;
9716
0
    g.IO.MousePos = g.IO.MousePosPrev = pos;
9717
0
    g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
9718
0
    g.IO.WantSetMousePos = true;
9719
    //IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
9720
0
}
9721
9722
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
9723
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9724
0
{
9725
0
    ImGuiContext& g = *GImGui;
9726
0
    if (g.BeginPopupStack.Size > 0)
9727
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9728
0
    return g.IO.MousePos;
9729
0
}
9730
9731
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9732
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9733
343k
{
9734
    // The assert is only to silence a false-positive in XCode Static Analysis.
9735
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9736
343k
    IM_ASSERT(GImGui != NULL);
9737
343k
    const float MOUSE_INVALID = -256000.0f;
9738
343k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9739
343k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9740
343k
}
9741
9742
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9743
bool ImGui::IsAnyMouseDown()
9744
0
{
9745
0
    ImGuiContext& g = *GImGui;
9746
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9747
0
        if (g.IO.MouseDown[n])
9748
0
            return true;
9749
0
    return false;
9750
0
}
9751
9752
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9753
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9754
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9755
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9756
0
{
9757
0
    ImGuiContext& g = *GImGui;
9758
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9759
0
    if (lock_threshold < 0.0f)
9760
0
        lock_threshold = g.IO.MouseDragThreshold;
9761
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9762
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9763
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9764
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9765
0
    return ImVec2(0.0f, 0.0f);
9766
0
}
9767
9768
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9769
0
{
9770
0
    ImGuiContext& g = *GImGui;
9771
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9772
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9773
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9774
0
}
9775
9776
// Get desired mouse cursor shape.
9777
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9778
// updated during the frame, and locked in EndFrame()/Render().
9779
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9780
ImGuiMouseCursor ImGui::GetMouseCursor()
9781
0
{
9782
0
    ImGuiContext& g = *GImGui;
9783
0
    return g.MouseCursor;
9784
0
}
9785
9786
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9787
34
{
9788
34
    ImGuiContext& g = *GImGui;
9789
34
    g.MouseCursor = cursor_type;
9790
34
}
9791
9792
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9793
563k
{
9794
563k
    IM_ASSERT(ImGui::IsAliasKey(key));
9795
563k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9796
563k
    key_data->Down = v;
9797
563k
    key_data->AnalogValue = analog_value;
9798
563k
}
9799
9800
// [Internal] Do not use directly
9801
static ImGuiKeyChord GetMergedModsFromKeys()
9802
161k
{
9803
161k
    ImGuiKeyChord mods = 0;
9804
161k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9805
161k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9806
161k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9807
161k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9808
161k
    return mods;
9809
161k
}
9810
9811
static void ImGui::UpdateKeyboardInputs()
9812
80.5k
{
9813
80.5k
    ImGuiContext& g = *GImGui;
9814
80.5k
    ImGuiIO& io = g.IO;
9815
9816
80.5k
    if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
9817
0
        io.ClearInputKeys();
9818
9819
    // Import legacy keys or verify they are not used
9820
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9821
    if (io.BackendUsingLegacyKeyArrays == 0)
9822
    {
9823
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9824
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9825
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9826
    }
9827
    else
9828
    {
9829
        if (g.FrameCount == 0)
9830
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9831
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9832
9833
        // Build reverse KeyMap (Named -> Legacy)
9834
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9835
            if (io.KeyMap[n] != -1)
9836
            {
9837
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9838
                io.KeyMap[io.KeyMap[n]] = n;
9839
            }
9840
9841
        // Import legacy keys into new ones
9842
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9843
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9844
            {
9845
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9846
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9847
                io.KeysData[key].Down = io.KeysDown[n];
9848
                if (key != n)
9849
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9850
                io.BackendUsingLegacyKeyArrays = 1;
9851
            }
9852
        if (io.BackendUsingLegacyKeyArrays == 1)
9853
        {
9854
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9855
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9856
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9857
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9858
        }
9859
    }
9860
#endif
9861
9862
    // Import legacy ImGuiNavInput_ io inputs and convert to gamepad keys
9863
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9864
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9865
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9866
    {
9867
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9868
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9869
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9870
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9871
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9872
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9873
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9874
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9875
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9876
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9877
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9878
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9879
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9880
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9881
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9882
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9883
        #undef NAV_MAP_KEY
9884
    }
9885
#endif
9886
9887
    // Update aliases
9888
483k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9889
402k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9890
80.5k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9891
80.5k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9892
9893
    // Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values.
9894
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9895
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9896
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9897
80.5k
    const ImGuiKeyChord prev_key_mods = io.KeyMods;
9898
80.5k
    io.KeyMods = GetMergedModsFromKeys();
9899
80.5k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9900
80.5k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9901
80.5k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9902
80.5k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9903
80.5k
    if (prev_key_mods != io.KeyMods)
9904
0
        g.LastKeyModsChangeTime = g.Time;
9905
80.5k
    if (prev_key_mods != io.KeyMods && prev_key_mods == 0)
9906
0
        g.LastKeyModsChangeFromNoneTime = g.Time;
9907
9908
    // Clear gamepad data if disabled
9909
80.5k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9910
2.01M
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9911
1.93M
        {
9912
1.93M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9913
1.93M
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9914
1.93M
        }
9915
9916
    // Update keys
9917
12.4M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9918
12.4M
    {
9919
12.4M
        ImGuiKeyData* key_data = &io.KeysData[i];
9920
12.4M
        key_data->DownDurationPrev = key_data->DownDuration;
9921
12.4M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9922
12.4M
        if (key_data->DownDuration == 0.0f)
9923
11.4k
        {
9924
11.4k
            ImGuiKey key = (ImGuiKey)(ImGuiKey_KeysData_OFFSET + i);
9925
11.4k
            if (IsKeyboardKey(key))
9926
5.28k
                g.LastKeyboardKeyPressTime = g.Time;
9927
6.15k
            else if (key == ImGuiKey_ReservedForModCtrl || key == ImGuiKey_ReservedForModShift || key == ImGuiKey_ReservedForModAlt || key == ImGuiKey_ReservedForModSuper)
9928
0
                g.LastKeyboardKeyPressTime = g.Time;
9929
11.4k
        }
9930
12.4M
    }
9931
9932
    // Update keys/input owner (named keys only): one entry per key
9933
12.4M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9934
12.4M
    {
9935
12.4M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9936
12.4M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9937
12.4M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9938
12.4M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9939
12.2M
            owner_data->OwnerNext = ImGuiKeyOwner_NoOwner;
9940
12.4M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9941
12.4M
    }
9942
9943
    // Update key routing (for e.g. shortcuts)
9944
80.5k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9945
80.5k
}
9946
9947
static void ImGui::UpdateMouseInputs()
9948
80.5k
{
9949
80.5k
    ImGuiContext& g = *GImGui;
9950
80.5k
    ImGuiIO& io = g.IO;
9951
9952
    // Mouse Wheel swapping flag
9953
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9954
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9955
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9956
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9957
80.5k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9958
9959
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9960
80.5k
    if (IsMousePosValid(&io.MousePos))
9961
65.8k
        io.MousePos = g.MouseLastValidPos = ImFloor(io.MousePos);
9962
9963
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9964
80.5k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9965
65.5k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9966
15.0k
    else
9967
15.0k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9968
9969
    // Update stationary timer.
9970
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9971
80.5k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9972
80.5k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9973
80.5k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9974
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9975
9976
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9977
80.5k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9978
4.12k
        g.NavDisableMouseHover = false;
9979
9980
483k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9981
402k
    {
9982
402k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9983
402k
        io.MouseClickedCount[i] = 0; // Will be filled below
9984
402k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9985
402k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9986
402k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9987
402k
        if (io.MouseClicked[i])
9988
4.55k
        {
9989
4.55k
            bool is_repeated_click = false;
9990
4.55k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9991
3.94k
            {
9992
3.94k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9993
3.94k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9994
3.64k
                    is_repeated_click = true;
9995
3.94k
            }
9996
4.55k
            if (is_repeated_click)
9997
3.64k
                io.MouseClickedLastCount[i]++;
9998
906
            else
9999
906
                io.MouseClickedLastCount[i] = 1;
10000
4.55k
            io.MouseClickedTime[i] = g.Time;
10001
4.55k
            io.MouseClickedPos[i] = io.MousePos;
10002
4.55k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
10003
4.55k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
10004
4.55k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
10005
4.55k
        }
10006
398k
        else if (io.MouseDown[i])
10007
79.4k
        {
10008
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
10009
79.4k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
10010
79.4k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
10011
79.4k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
10012
79.4k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
10013
79.4k
        }
10014
10015
        // We provide io.MouseDoubleClicked[] as a legacy service
10016
402k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
10017
10018
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
10019
402k
        if (io.MouseClicked[i])
10020
4.55k
            g.NavDisableMouseHover = false;
10021
402k
    }
10022
80.5k
}
10023
10024
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
10025
0
{
10026
0
    ImGuiContext& g = *GImGui;
10027
0
    if (window)
10028
0
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
10029
0
    else
10030
0
        g.WheelingWindowReleaseTimer = 0.0f;
10031
0
    if (g.WheelingWindow == window)
10032
0
        return;
10033
0
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
10034
0
    g.WheelingWindow = window;
10035
0
    g.WheelingWindowRefMousePos = g.IO.MousePos;
10036
0
    if (window == NULL)
10037
0
    {
10038
0
        g.WheelingWindowStartFrame = -1;
10039
0
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
10040
0
    }
10041
0
}
10042
10043
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
10044
57
{
10045
    // For each axis, find window in the hierarchy that may want to use scrolling
10046
57
    ImGuiContext& g = *GImGui;
10047
57
    ImGuiWindow* windows[2] = { NULL, NULL };
10048
171
    for (int axis = 0; axis < 2; axis++)
10049
114
        if (wheel[axis] != 0.0f)
10050
103
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
10051
2
            {
10052
                // Bubble up into parent window if:
10053
                // - a child window doesn't allow any scrolling.
10054
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
10055
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
10056
2
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
10057
2
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
10058
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
10059
2
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
10060
1
                    break; // select this window
10061
2
            }
10062
57
    if (windows[0] == NULL && windows[1] == NULL)
10063
0
        return NULL;
10064
10065
    // If there's only one window or only one axis then there's no ambiguity
10066
57
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
10067
56
        return windows[1] ? windows[1] : windows[0];
10068
10069
    // If candidate are different windows we need to decide which one to prioritize
10070
    // - First frame: only find a winner if one axis is zero.
10071
    // - Subsequent frames: only find a winner when one is more than the other.
10072
1
    if (g.WheelingWindowStartFrame == -1)
10073
1
        g.WheelingWindowStartFrame = g.FrameCount;
10074
1
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
10075
1
    {
10076
1
        g.WheelingWindowWheelRemainder = wheel;
10077
1
        return NULL;
10078
1
    }
10079
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
10080
1
}
10081
10082
// Called by NewFrame()
10083
void ImGui::UpdateMouseWheel()
10084
80.5k
{
10085
    // Reset the locked window if we move the mouse or after the timer elapses.
10086
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
10087
80.5k
    ImGuiContext& g = *GImGui;
10088
80.5k
    if (g.WheelingWindow != NULL)
10089
0
    {
10090
0
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
10091
0
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
10092
0
            g.WheelingWindowReleaseTimer = 0.0f;
10093
0
        if (g.WheelingWindowReleaseTimer <= 0.0f)
10094
0
            LockWheelingWindow(NULL, 0.0f);
10095
0
    }
10096
10097
80.5k
    ImVec2 wheel;
10098
80.5k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheelH : 0.0f;
10099
80.5k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_NoOwner) ? g.IO.MouseWheel : 0.0f;
10100
10101
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
10102
80.5k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
10103
80.5k
    if (!mouse_window || mouse_window->Collapsed)
10104
70.9k
        return;
10105
10106
    // Zoom / Scale window
10107
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
10108
9.60k
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
10109
0
    {
10110
0
        LockWheelingWindow(mouse_window, wheel.y);
10111
0
        ImGuiWindow* window = mouse_window;
10112
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
10113
0
        const float scale = new_font_scale / window->FontWindowScale;
10114
0
        window->FontWindowScale = new_font_scale;
10115
0
        if (window == window->RootWindow)
10116
0
        {
10117
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
10118
0
            SetWindowPos(window, window->Pos + offset, 0);
10119
0
            window->Size = ImTrunc(window->Size * scale);
10120
0
            window->SizeFull = ImTrunc(window->SizeFull * scale);
10121
0
        }
10122
0
        return;
10123
0
    }
10124
9.60k
    if (g.IO.KeyCtrl)
10125
0
        return;
10126
10127
    // Mouse wheel scrolling
10128
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
10129
9.60k
    if (g.IO.MouseWheelRequestAxisSwap)
10130
0
        wheel = ImVec2(wheel.y, 0.0f);
10131
10132
    // Maintain a rough average of moving magnitude on both axises
10133
    // FIXME: should by based on wall clock time rather than frame-counter
10134
9.60k
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
10135
9.60k
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
10136
10137
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
10138
9.60k
    wheel += g.WheelingWindowWheelRemainder;
10139
9.60k
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
10140
9.60k
    if (wheel.x == 0.0f && wheel.y == 0.0f)
10141
9.55k
        return;
10142
10143
    // Mouse wheel scrolling: find target and apply
10144
    // - don't renew lock if axis doesn't apply on the window.
10145
    // - select a main axis when both axises are being moved.
10146
57
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
10147
56
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
10148
56
        {
10149
56
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
10150
56
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
10151
0
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
10152
56
            if (do_scroll[ImGuiAxis_X])
10153
0
            {
10154
0
                LockWheelingWindow(window, wheel.x);
10155
0
                float max_step = window->InnerRect.GetWidth() * 0.67f;
10156
0
                float scroll_step = ImTrunc(ImMin(2 * window->CalcFontSize(), max_step));
10157
0
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
10158
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10159
0
            }
10160
56
            if (do_scroll[ImGuiAxis_Y])
10161
0
            {
10162
0
                LockWheelingWindow(window, wheel.y);
10163
0
                float max_step = window->InnerRect.GetHeight() * 0.67f;
10164
0
                float scroll_step = ImTrunc(ImMin(5 * window->CalcFontSize(), max_step));
10165
0
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
10166
0
                g.WheelingWindowScrolledFrame = g.FrameCount;
10167
0
            }
10168
56
        }
10169
57
}
10170
10171
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
10172
0
{
10173
0
    ImGuiContext& g = *GImGui;
10174
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
10175
0
}
10176
10177
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
10178
0
{
10179
0
    ImGuiContext& g = *GImGui;
10180
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
10181
0
}
10182
10183
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10184
static const char* GetInputSourceName(ImGuiInputSource source)
10185
0
{
10186
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad" };
10187
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
10188
0
    return input_source_names[source];
10189
0
}
10190
static const char* GetMouseSourceName(ImGuiMouseSource source)
10191
0
{
10192
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
10193
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
10194
0
    return mouse_source_names[source];
10195
0
}
10196
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
10197
0
{
10198
0
    ImGuiContext& g = *GImGui;
10199
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MousePos.MouseSource)); return; }
10200
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseButton.MouseSource)); return; }
10201
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
10202
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
10203
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
10204
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
10205
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
10206
0
}
10207
#endif
10208
10209
// Process input queue
10210
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
10211
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
10212
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
10213
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
10214
80.5k
{
10215
80.5k
    ImGuiContext& g = *GImGui;
10216
80.5k
    ImGuiIO& io = g.IO;
10217
10218
    // Only trickle chars<>key when working with InputText()
10219
    // FIXME: InputText() could parse event trail?
10220
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
10221
80.5k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
10222
10223
80.5k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
10224
80.5k
    int  mouse_button_changed = 0x00;
10225
80.5k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
10226
10227
80.5k
    int event_n = 0;
10228
111k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
10229
42.5k
    {
10230
42.5k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
10231
42.5k
        if (e->Type == ImGuiInputEventType_MousePos)
10232
7.24k
        {
10233
7.24k
            if (g.IO.WantSetMousePos)
10234
0
                continue;
10235
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
10236
7.24k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
10237
7.24k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
10238
2.06k
                break;
10239
5.17k
            io.MousePos = event_pos;
10240
5.17k
            io.MouseSource = e->MousePos.MouseSource;
10241
5.17k
            mouse_moved = true;
10242
5.17k
        }
10243
35.2k
        else if (e->Type == ImGuiInputEventType_MouseButton)
10244
14.2k
        {
10245
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10246
14.2k
            const ImGuiMouseButton button = e->MouseButton.Button;
10247
14.2k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
10248
14.2k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
10249
5.55k
                break;
10250
8.70k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
10251
0
                break;
10252
8.70k
            io.MouseDown[button] = e->MouseButton.Down;
10253
8.70k
            io.MouseSource = e->MouseButton.MouseSource;
10254
8.70k
            mouse_button_changed |= (1 << button);
10255
8.70k
        }
10256
21.0k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
10257
1.92k
        {
10258
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
10259
1.92k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
10260
660
                break;
10261
1.26k
            io.MouseWheelH += e->MouseWheel.WheelX;
10262
1.26k
            io.MouseWheel += e->MouseWheel.WheelY;
10263
1.26k
            io.MouseSource = e->MouseWheel.MouseSource;
10264
1.26k
            mouse_wheeled = true;
10265
1.26k
        }
10266
19.0k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
10267
0
        {
10268
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
10269
0
        }
10270
19.0k
        else if (e->Type == ImGuiInputEventType_Key)
10271
12.8k
        {
10272
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
10273
12.8k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10274
0
                continue;
10275
12.8k
            ImGuiKey key = e->Key.Key;
10276
12.8k
            IM_ASSERT(key != ImGuiKey_None);
10277
12.8k
            ImGuiKeyData* key_data = GetKeyData(key);
10278
12.8k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
10279
12.8k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
10280
2.98k
                break;
10281
9.90k
            key_data->Down = e->Key.Down;
10282
9.90k
            key_data->AnalogValue = e->Key.AnalogValue;
10283
9.90k
            key_changed = true;
10284
9.90k
            key_changed_mask.SetBit(key_data_index);
10285
10286
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
10287
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10288
            io.KeysDown[key_data_index] = key_data->Down;
10289
            if (io.KeyMap[key_data_index] != -1)
10290
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
10291
#endif
10292
9.90k
        }
10293
6.18k
        else if (e->Type == ImGuiInputEventType_Text)
10294
4.17k
        {
10295
4.17k
            if (io.ConfigFlags & ImGuiConfigFlags_NoKeyboard)
10296
0
                continue;
10297
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
10298
4.17k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
10299
440
                break;
10300
3.73k
            unsigned int c = e->Text.Char;
10301
3.73k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
10302
3.73k
            if (trickle_interleaved_keys_and_text)
10303
0
                text_inputted = true;
10304
3.73k
        }
10305
2.01k
        else if (e->Type == ImGuiInputEventType_Focus)
10306
2.01k
        {
10307
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
10308
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
10309
2.01k
            const bool focus_lost = !e->AppFocused.Focused;
10310
2.01k
            io.AppFocusLost = focus_lost;
10311
2.01k
        }
10312
0
        else
10313
0
        {
10314
0
            IM_ASSERT(0 && "Unknown event!");
10315
0
        }
10316
42.5k
    }
10317
10318
    // Record trail (for domain-specific applications wanting to access a precise trail)
10319
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
10320
111k
    for (int n = 0; n < event_n; n++)
10321
30.7k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
10322
10323
    // [DEBUG]
10324
80.5k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10325
80.5k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
10326
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
10327
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
10328
80.5k
#endif
10329
10330
    // Remaining events will be processed on the next frame
10331
80.5k
    if (event_n == g.InputEventsQueue.Size)
10332
68.8k
        g.InputEventsQueue.resize(0);
10333
11.7k
    else
10334
11.7k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
10335
10336
    // Clear buttons state when focus is lost
10337
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
10338
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
10339
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
10340
80.5k
    if (g.IO.AppFocusLost)
10341
2.00k
    {
10342
2.00k
        g.IO.ClearInputKeys();
10343
2.00k
        g.IO.ClearInputMouse();
10344
2.00k
    }
10345
80.5k
}
10346
10347
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
10348
16
{
10349
16
    if (!IsNamedKeyOrMod(key))
10350
0
        return ImGuiKeyOwner_NoOwner;
10351
10352
16
    ImGuiContext& g = *GImGui;
10353
16
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10354
16
    ImGuiID owner_id = owner_data->OwnerCurr;
10355
10356
16
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10357
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10358
0
            return ImGuiKeyOwner_NoOwner;
10359
10360
16
    return owner_id;
10361
16
}
10362
10363
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
10364
// TestKeyOwner(..., None) : (owner == None)
10365
// TestKeyOwner(..., Any)  : no owner test
10366
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
10367
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
10368
190k
{
10369
190k
    if (!IsNamedKeyOrMod(key))
10370
0
        return true;
10371
10372
190k
    ImGuiContext& g = *GImGui;
10373
190k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
10374
10.4k
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
10375
514
            return false;
10376
10377
190k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10378
190k
    if (owner_id == ImGuiKeyOwner_Any)
10379
17.2k
        return (owner_data->LockThisFrame == false);
10380
10381
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
10382
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
10383
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
10384
173k
    if (owner_data->OwnerCurr != owner_id)
10385
93
    {
10386
93
        if (owner_data->LockThisFrame)
10387
0
            return false;
10388
93
        if (owner_data->OwnerCurr != ImGuiKeyOwner_NoOwner)
10389
0
            return false;
10390
93
    }
10391
10392
173k
    return true;
10393
173k
}
10394
10395
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
10396
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
10397
// - SetKeyOwner(..., None)              : clears owner
10398
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
10399
// - SetKeyOwner(..., Any or None, Lock) : set lock
10400
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
10401
93
{
10402
93
    ImGuiContext& g = *GImGui;
10403
93
    IM_ASSERT(IsNamedKeyOrMod(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
10404
93
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
10405
    //IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags);
10406
10407
93
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
10408
93
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
10409
10410
    // We cannot lock by default as it would likely break lots of legacy code.
10411
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
10412
93
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
10413
93
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
10414
93
}
10415
10416
// Rarely used helper
10417
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
10418
0
{
10419
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
10420
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
10421
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
10422
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
10423
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
10424
0
}
10425
10426
// This is more or less equivalent to:
10427
//   if (IsItemHovered() || IsItemActive())
10428
//       SetKeyOwner(key, GetItemID());
10429
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
10430
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
10431
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
10432
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
10433
0
{
10434
0
    ImGuiContext& g = *GImGui;
10435
0
    ImGuiID id = g.LastItemData.ID;
10436
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
10437
0
        return;
10438
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
10439
0
        flags |= ImGuiInputFlags_CondDefault_;
10440
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
10441
0
    {
10442
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
10443
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
10444
0
    }
10445
0
}
10446
10447
void ImGui::SetItemKeyOwner(ImGuiKey key)
10448
0
{
10449
0
    SetItemKeyOwner(key, ImGuiInputFlags_None);
10450
0
}
10451
10452
// This is the only public API until we expose owner_id versions of the API as replacements.
10453
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord)
10454
0
{
10455
0
    return IsKeyChordPressed(key_chord, ImGuiInputFlags_None, ImGuiKeyOwner_Any);
10456
0
}
10457
10458
// This is equivalent to comparing KeyMods + doing a IsKeyPressed()
10459
bool ImGui::IsKeyChordPressed(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10460
161k
{
10461
161k
    ImGuiContext& g = *GImGui;
10462
161k
    key_chord = FixupKeyChord(key_chord);
10463
161k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
10464
161k
    if (g.IO.KeyMods != mods)
10465
161k
        return false;
10466
10467
    // Special storage location for mods
10468
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
10469
0
    if (key == ImGuiKey_None)
10470
0
        key = ConvertSingleModFlagToKey(mods);
10471
0
    if (!IsKeyPressed(key, (flags & ImGuiInputFlags_RepeatMask_), owner_id))
10472
0
        return false;
10473
0
    return true;
10474
0
}
10475
10476
void ImGui::SetNextItemShortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10477
0
{
10478
0
    ImGuiContext& g = *GImGui;
10479
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasShortcut;
10480
0
    g.NextItemData.Shortcut = key_chord;
10481
0
    g.NextItemData.ShortcutFlags = flags;
10482
0
}
10483
10484
// Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData
10485
void ImGui::ItemHandleShortcut(ImGuiID id)
10486
0
{
10487
0
    ImGuiContext& g = *GImGui;
10488
0
    ImGuiInputFlags flags = g.NextItemData.ShortcutFlags;
10489
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetNextItemShortcut) == 0); // Passing flags not supported by SetNextItemShortcut()!
10490
10491
0
    if (g.LastItemData.InFlags & ImGuiItemFlags_Disabled)
10492
0
        return;
10493
0
    if (flags & ImGuiInputFlags_Tooltip)
10494
0
    {
10495
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasShortcut;
10496
0
        g.LastItemData.Shortcut = g.NextItemData.Shortcut;
10497
0
    }
10498
0
    if (!Shortcut(g.NextItemData.Shortcut, flags & ImGuiInputFlags_SupportedByShortcut, id) || g.NavActivateId != 0)
10499
0
        return;
10500
10501
    // FIXME: Generalize Activation queue?
10502
0
    g.NavActivateId = id; // Will effectively disable clipping.
10503
0
    g.NavActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_FromShortcut;
10504
    //if (g.ActiveId == 0 || g.ActiveId == id)
10505
0
    g.NavActivateDownId = g.NavActivatePressedId = id;
10506
0
    NavHighlightActivated(id);
10507
0
}
10508
10509
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags)
10510
0
{
10511
0
    return Shortcut(key_chord, flags, ImGuiKeyOwner_Any);
10512
0
}
10513
10514
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiInputFlags flags, ImGuiID owner_id)
10515
161k
{
10516
161k
    ImGuiContext& g = *GImGui;
10517
    //IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id);
10518
10519
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
10520
161k
    if ((flags & ImGuiInputFlags_RouteTypeMask_) == 0)
10521
0
        flags |= ImGuiInputFlags_RouteFocused;
10522
10523
    // Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
10524
    // Effectively makes Shortcut() always input-owner aware.
10525
161k
    if (owner_id == ImGuiKeyOwner_Any || owner_id == ImGuiKeyOwner_NoOwner)
10526
0
        owner_id = GetRoutingIdFromOwnerId(owner_id);
10527
10528
161k
    if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10529
0
        return false;
10530
10531
    // Submit route
10532
161k
    if (!SetShortcutRouting(key_chord, flags, owner_id))
10533
0
        return false;
10534
10535
    // Default repeat behavior for Shortcut()
10536
    // So e.g. pressing Ctrl+W and releasing Ctrl while holding W will not trigger the W shortcut.
10537
161k
    if ((flags & ImGuiInputFlags_Repeat) != 0 && (flags & ImGuiInputFlags_RepeatUntilMask_) == 0)
10538
161k
        flags |= ImGuiInputFlags_RepeatUntilKeyModsChange;
10539
10540
161k
    if (!IsKeyChordPressed(key_chord, flags, owner_id))
10541
161k
        return false;
10542
10543
    // Claim mods during the press
10544
0
    SetKeyOwnersForKeyChord(key_chord & ImGuiMod_Mask_, owner_id);
10545
10546
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
10547
0
    return true;
10548
161k
}
10549
10550
10551
//-----------------------------------------------------------------------------
10552
// [SECTION] ERROR CHECKING
10553
//-----------------------------------------------------------------------------
10554
10555
// Verify ABI compatibility between caller code and compiled version of Dear ImGui. This helps detects some build issues.
10556
// Called by IMGUI_CHECKVERSION().
10557
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
10558
// If this triggers you have mismatched headers and compiled code versions.
10559
// - It could be because of a build issue (using new headers with old compiled code)
10560
// - It could be because of mismatched configuration #define, compilation settings, packing pragma etc.
10561
//   THE CONFIGURATION SETTINGS MENTIONED IN imconfig.h MUST BE SET FOR ALL COMPILATION UNITS INVOLVED WITH DEAR IMGUI.
10562
//   Which is why it is required you put them in your imconfig file (and NOT only before including imgui.h).
10563
//   Otherwise it is possible that different compilation units would see different structure layout.
10564
//   If you don't want to modify imconfig.h you can use the IMGUI_USER_CONFIG define to change filename.
10565
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
10566
1
{
10567
1
    bool error = false;
10568
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
10569
1
    if (sz_io    != sizeof(ImGuiIO))    { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
10570
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
10571
1
    if (sz_vec2  != sizeof(ImVec2))     { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
10572
1
    if (sz_vec4  != sizeof(ImVec4))     { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
10573
1
    if (sz_vert  != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
10574
1
    if (sz_idx   != sizeof(ImDrawIdx))  { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
10575
1
    return !error;
10576
1
}
10577
10578
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
10579
// This is causing issues and ambiguity and we need to retire that.
10580
// See https://github.com/ocornut/imgui/issues/5548 for more details.
10581
// [Scenario 1]
10582
//  Previously this would make the window content size ~200x200:
10583
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
10584
//  Instead, please submit an item:
10585
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
10586
//  Alternative:
10587
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
10588
// [Scenario 2]
10589
//  For reference this is one of the issue what we aim to fix with this change:
10590
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
10591
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
10592
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
10593
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
10594
0
{
10595
0
    ImGuiContext& g = *GImGui;
10596
0
    ImGuiWindow* window = g.CurrentWindow;
10597
0
    IM_ASSERT(window->DC.IsSetPos);
10598
0
    window->DC.IsSetPos = false;
10599
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
10600
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
10601
0
        return;
10602
0
    if (window->SkipItems)
10603
0
        return;
10604
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
10605
#else
10606
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10607
#endif
10608
0
}
10609
10610
static void ImGui::ErrorCheckNewFrameSanityChecks()
10611
80.5k
{
10612
80.5k
    ImGuiContext& g = *GImGui;
10613
10614
    // Check user IM_ASSERT macro
10615
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
10616
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
10617
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
10618
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
10619
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
10620
80.5k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
10621
10622
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
10623
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
10624
#ifdef __EMSCRIPTEN__
10625
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
10626
        g.IO.DeltaTime = 0.00001f;
10627
#endif
10628
10629
    // Check user data
10630
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
10631
80.5k
    IM_ASSERT(g.Initialized);
10632
80.5k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
10633
80.5k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
10634
80.5k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
10635
80.5k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
10636
80.5k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
10637
80.5k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
10638
80.5k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
10639
80.5k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
10640
80.5k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
10641
80.5k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
10642
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
10643
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
10644
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
10645
10646
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
10647
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
10648
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
10649
#endif
10650
10651
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
10652
80.5k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
10653
80.5k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10654
80.5k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
10655
80.5k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
10656
10657
    // Perform simple checks: multi-viewport and platform windows support
10658
80.5k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
10659
1
    {
10660
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
10661
0
        {
10662
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
10663
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
10664
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
10665
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
10666
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
10667
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
10668
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
10669
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
10670
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
10671
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
10672
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
10673
0
        }
10674
1
        else
10675
1
        {
10676
            // Disable feature, our backends do not support it
10677
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
10678
1
        }
10679
10680
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
10681
1
        for (ImGuiPlatformMonitor& mon : g.PlatformIO.Monitors)
10682
0
        {
10683
0
            IM_UNUSED(mon);
10684
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
10685
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
10686
0
            IM_ASSERT(mon.DpiScale != 0.0f);
10687
0
        }
10688
1
    }
10689
80.5k
}
10690
10691
static void ImGui::ErrorCheckEndFrameSanityChecks()
10692
80.5k
{
10693
80.5k
    ImGuiContext& g = *GImGui;
10694
10695
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
10696
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
10697
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
10698
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
10699
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
10700
    // while still correctly asserting on mid-frame key press events.
10701
80.5k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
10702
80.5k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
10703
80.5k
    IM_UNUSED(key_mods);
10704
10705
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
10706
    //ErrorCheckEndFrameRecover();
10707
10708
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
10709
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
10710
80.5k
    if (g.CurrentWindowStack.Size != 1)
10711
0
    {
10712
0
        if (g.CurrentWindowStack.Size > 1)
10713
0
        {
10714
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
10715
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
10716
0
            IM_UNUSED(window);
10717
0
            while (g.CurrentWindowStack.Size > 1)
10718
0
                End();
10719
0
        }
10720
0
        else
10721
0
        {
10722
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
10723
0
        }
10724
0
    }
10725
10726
80.5k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
10727
80.5k
}
10728
10729
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
10730
// Must be called during or before EndFrame().
10731
// This is generally flawed as we are not necessarily End/Popping things in the right order.
10732
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
10733
// FIXME: Can't recover from interleaved BeginTabBar/Begin
10734
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10735
0
{
10736
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
10737
0
    ImGuiContext& g = *GImGui;
10738
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
10739
0
    {
10740
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
10741
0
        ImGuiWindow* window = g.CurrentWindow;
10742
0
        if (g.CurrentWindowStack.Size == 1)
10743
0
        {
10744
0
            IM_ASSERT(window->IsFallbackWindow);
10745
0
            break;
10746
0
        }
10747
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
10748
0
        {
10749
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
10750
0
            EndChild();
10751
0
        }
10752
0
        else
10753
0
        {
10754
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
10755
0
            End();
10756
0
        }
10757
0
    }
10758
0
}
10759
10760
// Must be called before End()/EndChild()
10761
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
10762
0
{
10763
0
    ImGuiContext& g = *GImGui;
10764
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
10765
0
    {
10766
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
10767
0
        EndTable();
10768
0
    }
10769
10770
0
    ImGuiWindow* window = g.CurrentWindow;
10771
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
10772
0
    IM_ASSERT(window != NULL);
10773
0
    while (g.CurrentTabBar != NULL) //-V1044
10774
0
    {
10775
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
10776
0
        EndTabBar();
10777
0
    }
10778
0
    while (g.CurrentMultiSelect != NULL && g.CurrentMultiSelect->Storage->Window == window)
10779
0
    {
10780
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndMultiSelect() in '%s'", window->Name);
10781
0
        EndMultiSelect();
10782
0
    }
10783
0
    while (window->DC.TreeDepth > 0)
10784
0
    {
10785
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
10786
0
        TreePop();
10787
0
    }
10788
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
10789
0
    {
10790
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
10791
0
        EndGroup();
10792
0
    }
10793
0
    while (window->IDStack.Size > 1)
10794
0
    {
10795
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
10796
0
        PopID();
10797
0
    }
10798
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
10799
0
    {
10800
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
10801
0
        if (g.CurrentItemFlags & ImGuiItemFlags_Disabled)
10802
0
            EndDisabled();
10803
0
        else
10804
0
        {
10805
0
            EndDisabledOverrideReenable();
10806
0
            g.CurrentWindowStack.back().DisabledOverrideReenable = false;
10807
0
        }
10808
0
    }
10809
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
10810
0
    {
10811
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
10812
0
        PopStyleColor();
10813
0
    }
10814
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
10815
0
    {
10816
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
10817
0
        PopItemFlag();
10818
0
    }
10819
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
10820
0
    {
10821
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
10822
0
        PopStyleVar();
10823
0
    }
10824
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
10825
0
    {
10826
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
10827
0
        PopFont();
10828
0
    }
10829
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
10830
0
    {
10831
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
10832
0
        PopFocusScope();
10833
0
    }
10834
0
}
10835
10836
// Save current stack sizes for later compare
10837
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10838
186k
{
10839
186k
    ImGuiContext& g = *ctx;
10840
186k
    ImGuiWindow* window = g.CurrentWindow;
10841
186k
    SizeOfIDStack = (short)window->IDStack.Size;
10842
186k
    SizeOfColorStack = (short)g.ColorStack.Size;
10843
186k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10844
186k
    SizeOfFontStack = (short)g.FontStack.Size;
10845
186k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10846
186k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10847
186k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10848
186k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10849
186k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10850
186k
}
10851
10852
// Compare to detect usage errors
10853
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10854
186k
{
10855
186k
    ImGuiContext& g = *ctx;
10856
186k
    ImGuiWindow* window = g.CurrentWindow;
10857
186k
    IM_UNUSED(window);
10858
10859
    // Window stacks
10860
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10861
186k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10862
10863
    // Global stacks
10864
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10865
186k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10866
186k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10867
186k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10868
186k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10869
186k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10870
186k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10871
186k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10872
186k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10873
186k
}
10874
10875
//-----------------------------------------------------------------------------
10876
// [SECTION] ITEM SUBMISSION
10877
//-----------------------------------------------------------------------------
10878
// - KeepAliveID()
10879
// - ItemAdd()
10880
//-----------------------------------------------------------------------------
10881
10882
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
10883
void ImGui::KeepAliveID(ImGuiID id)
10884
357k
{
10885
357k
    ImGuiContext& g = *GImGui;
10886
357k
    if (g.ActiveId == id)
10887
8.79k
        g.ActiveIdIsAlive = id;
10888
357k
    if (g.ActiveIdPreviousFrame == id)
10889
8.79k
        g.ActiveIdPreviousFrameIsAlive = true;
10890
357k
}
10891
10892
// Declare item bounding box for clipping and interaction.
10893
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10894
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10895
// THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN)
10896
IM_MSVC_RUNTIME_CHECKS_OFF
10897
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10898
374k
{
10899
374k
    ImGuiContext& g = *GImGui;
10900
374k
    ImGuiWindow* window = g.CurrentWindow;
10901
10902
    // Set item data
10903
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10904
374k
    g.LastItemData.ID = id;
10905
374k
    g.LastItemData.Rect = bb;
10906
374k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10907
374k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10908
374k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10909
    // Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared.
10910
10911
374k
    if (id != 0)
10912
349k
    {
10913
349k
        KeepAliveID(id);
10914
10915
        // Directional navigation processing
10916
        // Runs prior to clipping early-out
10917
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10918
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10919
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10920
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10921
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10922
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10923
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10924
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10925
349k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10926
182k
        {
10927
            // FIMXE-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test.
10928
182k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10929
182k
            if (g.NavId == id || g.NavAnyRequest)
10930
14.0k
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10931
1.00k
                    if (window == g.NavWindow || ((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened))
10932
1.00k
                        NavProcessItem();
10933
182k
        }
10934
10935
349k
        if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasShortcut)
10936
0
            ItemHandleShortcut(id);
10937
349k
    }
10938
10939
    // Lightweight clear of SetNextItemXXX data.
10940
374k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10941
374k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10942
10943
#ifdef IMGUI_ENABLE_TEST_ENGINE
10944
    if (id != 0)
10945
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10946
#endif
10947
10948
    // Clipping test
10949
    // (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false')
10950
    // g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts)
10951
374k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10952
374k
    if (!is_rect_visible)
10953
73.0k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId && id != g.NavActivateId))
10954
72.8k
            if (!g.ItemUnclipByLog)
10955
72.8k
                return false;
10956
10957
    // [DEBUG]
10958
301k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10959
301k
    if (id != 0)
10960
298k
    {
10961
298k
        if (id == g.DebugLocateId)
10962
0
            DebugLocateItemResolveWithLastItem();
10963
10964
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10965
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10966
        // READ THE FAQ: https://dearimgui.com/faq
10967
298k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10968
298k
    }
10969
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10970
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10971
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10972
301k
#endif
10973
10974
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10975
301k
    if (is_rect_visible)
10976
301k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10977
301k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10978
4.02k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10979
301k
    return true;
10980
374k
}
10981
IM_MSVC_RUNTIME_CHECKS_RESTORE
10982
10983
//-----------------------------------------------------------------------------
10984
// [SECTION] LAYOUT
10985
//-----------------------------------------------------------------------------
10986
// - ItemSize()
10987
// - SameLine()
10988
// - GetCursorScreenPos()
10989
// - SetCursorScreenPos()
10990
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10991
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10992
// - GetCursorStartPos()
10993
// - Indent()
10994
// - Unindent()
10995
// - SetNextItemWidth()
10996
// - PushItemWidth()
10997
// - PushMultiItemsWidths()
10998
// - PopItemWidth()
10999
// - CalcItemWidth()
11000
// - CalcItemSize()
11001
// - GetTextLineHeight()
11002
// - GetTextLineHeightWithSpacing()
11003
// - GetFrameHeight()
11004
// - GetFrameHeightWithSpacing()
11005
// - GetContentRegionMax()
11006
// - GetContentRegionAvail(),
11007
// - BeginGroup()
11008
// - EndGroup()
11009
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
11010
//-----------------------------------------------------------------------------
11011
11012
// Advance cursor given item size for layout.
11013
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
11014
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
11015
// THIS IS IN THE PERFORMANCE CRITICAL PATH.
11016
IM_MSVC_RUNTIME_CHECKS_OFF
11017
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
11018
50.3k
{
11019
50.3k
    ImGuiContext& g = *GImGui;
11020
50.3k
    ImGuiWindow* window = g.CurrentWindow;
11021
50.3k
    if (window->SkipItems)
11022
0
        return;
11023
11024
    // We increase the height in this function to accommodate for baseline offset.
11025
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
11026
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
11027
50.3k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
11028
11029
50.3k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
11030
50.3k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
11031
11032
    // Always align ourselves on pixel boundaries
11033
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
11034
50.3k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
11035
50.3k
    window->DC.CursorPosPrevLine.y = line_y1;
11036
50.3k
    window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
11037
50.3k
    window->DC.CursorPos.y = IM_TRUNC(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
11038
50.3k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
11039
50.3k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
11040
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
11041
11042
50.3k
    window->DC.PrevLineSize.y = line_height;
11043
50.3k
    window->DC.CurrLineSize.y = 0.0f;
11044
50.3k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
11045
50.3k
    window->DC.CurrLineTextBaseOffset = 0.0f;
11046
50.3k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
11047
11048
    // Horizontal layout mode
11049
50.3k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
11050
0
        SameLine();
11051
50.3k
}
11052
IM_MSVC_RUNTIME_CHECKS_RESTORE
11053
11054
// Gets back to previous line and continue with horizontal layout
11055
//      offset_from_start_x == 0 : follow right after previous item
11056
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
11057
//      spacing_w < 0            : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0
11058
//      spacing_w >= 0           : enforce spacing amount
11059
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
11060
0
{
11061
0
    ImGuiContext& g = *GImGui;
11062
0
    ImGuiWindow* window = g.CurrentWindow;
11063
0
    if (window->SkipItems)
11064
0
        return;
11065
11066
0
    if (offset_from_start_x != 0.0f)
11067
0
    {
11068
0
        if (spacing_w < 0.0f)
11069
0
            spacing_w = 0.0f;
11070
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
11071
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11072
0
    }
11073
0
    else
11074
0
    {
11075
0
        if (spacing_w < 0.0f)
11076
0
            spacing_w = g.Style.ItemSpacing.x;
11077
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
11078
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
11079
0
    }
11080
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
11081
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
11082
0
    window->DC.IsSameLine = true;
11083
0
}
11084
11085
ImVec2 ImGui::GetCursorScreenPos()
11086
47.4k
{
11087
47.4k
    ImGuiWindow* window = GetCurrentWindowRead();
11088
47.4k
    return window->DC.CursorPos;
11089
47.4k
}
11090
11091
void ImGui::SetCursorScreenPos(const ImVec2& pos)
11092
0
{
11093
0
    ImGuiWindow* window = GetCurrentWindow();
11094
0
    window->DC.CursorPos = pos;
11095
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11096
0
    window->DC.IsSetPos = true;
11097
0
}
11098
11099
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
11100
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
11101
ImVec2 ImGui::GetCursorPos()
11102
0
{
11103
0
    ImGuiWindow* window = GetCurrentWindowRead();
11104
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
11105
0
}
11106
11107
float ImGui::GetCursorPosX()
11108
0
{
11109
0
    ImGuiWindow* window = GetCurrentWindowRead();
11110
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
11111
0
}
11112
11113
float ImGui::GetCursorPosY()
11114
0
{
11115
0
    ImGuiWindow* window = GetCurrentWindowRead();
11116
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
11117
0
}
11118
11119
void ImGui::SetCursorPos(const ImVec2& local_pos)
11120
0
{
11121
0
    ImGuiWindow* window = GetCurrentWindow();
11122
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
11123
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
11124
0
    window->DC.IsSetPos = true;
11125
0
}
11126
11127
void ImGui::SetCursorPosX(float x)
11128
0
{
11129
0
    ImGuiWindow* window = GetCurrentWindow();
11130
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
11131
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
11132
0
    window->DC.IsSetPos = true;
11133
0
}
11134
11135
void ImGui::SetCursorPosY(float y)
11136
0
{
11137
0
    ImGuiWindow* window = GetCurrentWindow();
11138
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
11139
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
11140
0
    window->DC.IsSetPos = true;
11141
0
}
11142
11143
ImVec2 ImGui::GetCursorStartPos()
11144
0
{
11145
0
    ImGuiWindow* window = GetCurrentWindowRead();
11146
0
    return window->DC.CursorStartPos - window->Pos;
11147
0
}
11148
11149
void ImGui::Indent(float indent_w)
11150
0
{
11151
0
    ImGuiContext& g = *GImGui;
11152
0
    ImGuiWindow* window = GetCurrentWindow();
11153
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11154
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11155
0
}
11156
11157
void ImGui::Unindent(float indent_w)
11158
0
{
11159
0
    ImGuiContext& g = *GImGui;
11160
0
    ImGuiWindow* window = GetCurrentWindow();
11161
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
11162
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
11163
0
}
11164
11165
// Affect large frame+labels widgets only.
11166
void ImGui::SetNextItemWidth(float item_width)
11167
0
{
11168
0
    ImGuiContext& g = *GImGui;
11169
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
11170
0
    g.NextItemData.Width = item_width;
11171
0
}
11172
11173
// FIXME: Remove the == 0.0f behavior?
11174
void ImGui::PushItemWidth(float item_width)
11175
0
{
11176
0
    ImGuiContext& g = *GImGui;
11177
0
    ImGuiWindow* window = g.CurrentWindow;
11178
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11179
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
11180
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11181
0
}
11182
11183
void ImGui::PushMultiItemsWidths(int components, float w_full)
11184
0
{
11185
0
    ImGuiContext& g = *GImGui;
11186
0
    ImGuiWindow* window = g.CurrentWindow;
11187
0
    IM_ASSERT(components > 0);
11188
0
    const ImGuiStyle& style = g.Style;
11189
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
11190
0
    float w_items = w_full - style.ItemInnerSpacing.x * (components - 1);
11191
0
    float prev_split = w_items;
11192
0
    for (int i = components - 1; i > 0; i--)
11193
0
    {
11194
0
        float next_split = IM_TRUNC(w_items * i / components);
11195
0
        window->DC.ItemWidthStack.push_back(ImMax(prev_split - next_split, 1.0f));
11196
0
        prev_split = next_split;
11197
0
    }
11198
0
    window->DC.ItemWidth = ImMax(prev_split, 1.0f);
11199
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
11200
0
}
11201
11202
void ImGui::PopItemWidth()
11203
0
{
11204
0
    ImGuiWindow* window = GetCurrentWindow();
11205
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
11206
0
    window->DC.ItemWidthStack.pop_back();
11207
0
}
11208
11209
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
11210
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
11211
float ImGui::CalcItemWidth()
11212
0
{
11213
0
    ImGuiContext& g = *GImGui;
11214
0
    ImGuiWindow* window = g.CurrentWindow;
11215
0
    float w;
11216
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
11217
0
        w = g.NextItemData.Width;
11218
0
    else
11219
0
        w = window->DC.ItemWidth;
11220
0
    if (w < 0.0f)
11221
0
    {
11222
0
        float region_avail_x = GetContentRegionAvail().x;
11223
0
        w = ImMax(1.0f, region_avail_x + w);
11224
0
    }
11225
0
    w = IM_TRUNC(w);
11226
0
    return w;
11227
0
}
11228
11229
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
11230
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
11231
// Note that only CalcItemWidth() is publicly exposed.
11232
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
11233
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
11234
25.3k
{
11235
25.3k
    ImVec2 avail;
11236
25.3k
    if (size.x < 0.0f || size.y < 0.0f)
11237
0
        avail = GetContentRegionAvail();
11238
11239
25.3k
    if (size.x == 0.0f)
11240
3.48k
        size.x = default_w;
11241
21.8k
    else if (size.x < 0.0f)
11242
0
        size.x = ImMax(4.0f, avail.x + size.x); // <-- size.x is negative here so we are subtracting
11243
11244
25.3k
    if (size.y == 0.0f)
11245
3.26k
        size.y = default_h;
11246
22.0k
    else if (size.y < 0.0f)
11247
0
        size.y = ImMax(4.0f, avail.y + size.y); // <-- size.y is negative here so we are subtracting
11248
11249
25.3k
    return size;
11250
25.3k
}
11251
11252
float ImGui::GetTextLineHeight()
11253
0
{
11254
0
    ImGuiContext& g = *GImGui;
11255
0
    return g.FontSize;
11256
0
}
11257
11258
float ImGui::GetTextLineHeightWithSpacing()
11259
25.3k
{
11260
25.3k
    ImGuiContext& g = *GImGui;
11261
25.3k
    return g.FontSize + g.Style.ItemSpacing.y;
11262
25.3k
}
11263
11264
float ImGui::GetFrameHeight()
11265
4.97k
{
11266
4.97k
    ImGuiContext& g = *GImGui;
11267
4.97k
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
11268
4.97k
}
11269
11270
float ImGui::GetFrameHeightWithSpacing()
11271
0
{
11272
0
    ImGuiContext& g = *GImGui;
11273
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
11274
0
}
11275
11276
ImVec2 ImGui::GetContentRegionAvail()
11277
25.3k
{
11278
25.3k
    ImGuiContext& g = *GImGui;
11279
25.3k
    ImGuiWindow* window = g.CurrentWindow;
11280
25.3k
    ImVec2 mx = (window->DC.CurrentColumns || g.CurrentTable) ? window->WorkRect.Max : window->ContentRegionRect.Max;
11281
25.3k
    return mx - window->DC.CursorPos;
11282
25.3k
}
11283
11284
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
11285
11286
// You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()!
11287
// They are bizarre local-coordinates which don't play well with scrolling.
11288
ImVec2 ImGui::GetContentRegionMax()
11289
{
11290
    return GetContentRegionAvail() + GetCursorScreenPos() - GetWindowPos();
11291
}
11292
11293
ImVec2 ImGui::GetWindowContentRegionMin()
11294
{
11295
    ImGuiWindow* window = GImGui->CurrentWindow;
11296
    return window->ContentRegionRect.Min - window->Pos;
11297
}
11298
11299
ImVec2 ImGui::GetWindowContentRegionMax()
11300
{
11301
    ImGuiWindow* window = GImGui->CurrentWindow;
11302
    return window->ContentRegionRect.Max - window->Pos;
11303
}
11304
#endif
11305
11306
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
11307
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
11308
// FIXME-OPT: Could we safely early out on ->SkipItems?
11309
void ImGui::BeginGroup()
11310
0
{
11311
0
    ImGuiContext& g = *GImGui;
11312
0
    ImGuiWindow* window = g.CurrentWindow;
11313
11314
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
11315
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11316
0
    group_data.WindowID = window->ID;
11317
0
    group_data.BackupCursorPos = window->DC.CursorPos;
11318
0
    group_data.BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
11319
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
11320
0
    group_data.BackupIndent = window->DC.Indent;
11321
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
11322
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
11323
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
11324
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
11325
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
11326
0
    group_data.BackupIsSameLine = window->DC.IsSameLine;
11327
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
11328
0
    group_data.EmitItem = true;
11329
11330
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
11331
0
    window->DC.Indent = window->DC.GroupOffset;
11332
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
11333
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
11334
0
    if (g.LogEnabled)
11335
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11336
0
}
11337
11338
void ImGui::EndGroup()
11339
0
{
11340
0
    ImGuiContext& g = *GImGui;
11341
0
    ImGuiWindow* window = g.CurrentWindow;
11342
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
11343
11344
0
    ImGuiGroupData& group_data = g.GroupStack.back();
11345
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
11346
11347
0
    if (window->DC.IsSetPos)
11348
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
11349
11350
    // Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543)
11351
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(ImMax(window->DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos));
11352
0
    window->DC.CursorPos = group_data.BackupCursorPos;
11353
0
    window->DC.CursorPosPrevLine = group_data.BackupCursorPosPrevLine;
11354
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, group_bb.Max);
11355
0
    window->DC.Indent = group_data.BackupIndent;
11356
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
11357
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
11358
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
11359
0
    window->DC.IsSameLine = group_data.BackupIsSameLine;
11360
0
    if (g.LogEnabled)
11361
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
11362
11363
0
    if (!group_data.EmitItem)
11364
0
    {
11365
0
        g.GroupStack.pop_back();
11366
0
        return;
11367
0
    }
11368
11369
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
11370
0
    ItemSize(group_bb.GetSize());
11371
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
11372
11373
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
11374
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
11375
    // Also if you grep for LastItemId you'll notice it is only used in that context.
11376
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
11377
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
11378
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
11379
0
    if (group_contains_curr_active_id)
11380
0
        g.LastItemData.ID = g.ActiveId;
11381
0
    else if (group_contains_prev_active_id)
11382
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
11383
0
    g.LastItemData.Rect = group_bb;
11384
11385
    // Forward Hovered flag
11386
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
11387
0
    if (group_contains_curr_hovered_id)
11388
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
11389
11390
    // Forward Edited flag
11391
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
11392
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
11393
11394
    // Forward Deactivated flag
11395
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
11396
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
11397
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
11398
11399
0
    g.GroupStack.pop_back();
11400
0
    if (g.DebugShowGroupRects)
11401
0
        window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
11402
0
}
11403
11404
11405
//-----------------------------------------------------------------------------
11406
// [SECTION] SCROLLING
11407
//-----------------------------------------------------------------------------
11408
11409
// Helper to snap on edges when aiming at an item very close to the edge,
11410
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
11411
// When we refactor the scrolling API this may be configurable with a flag?
11412
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
11413
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
11414
0
{
11415
0
    if (target <= snap_min + snap_threshold)
11416
0
        return ImLerp(snap_min, target, center_ratio);
11417
0
    if (target >= snap_max - snap_threshold)
11418
0
        return ImLerp(target, snap_max, center_ratio);
11419
0
    return target;
11420
0
}
11421
11422
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
11423
186k
{
11424
186k
    ImVec2 scroll = window->Scroll;
11425
186k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
11426
559k
    for (int axis = 0; axis < 2; axis++)
11427
372k
    {
11428
372k
        if (window->ScrollTarget[axis] < FLT_MAX)
11429
10.7k
        {
11430
10.7k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
11431
10.7k
            float scroll_target = window->ScrollTarget[axis];
11432
10.7k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
11433
0
            {
11434
0
                float snap_min = 0.0f;
11435
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
11436
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
11437
0
            }
11438
10.7k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
11439
10.7k
        }
11440
372k
        scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f));
11441
372k
        if (!window->Collapsed && !window->SkipItems)
11442
261k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
11443
372k
    }
11444
186k
    return scroll;
11445
186k
}
11446
11447
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
11448
0
{
11449
0
    ImGuiContext& g = *GImGui;
11450
0
    ImGuiWindow* window = g.CurrentWindow;
11451
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
11452
0
}
11453
11454
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11455
0
{
11456
0
    ScrollToRectEx(window, item_rect, flags);
11457
0
}
11458
11459
// Scroll to keep newly navigated item fully into view
11460
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
11461
0
{
11462
0
    ImGuiContext& g = *GImGui;
11463
0
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
11464
0
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
11465
0
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
11466
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
11467
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
11468
11469
    // Check that only one behavior is selected per axis
11470
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
11471
0
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
11472
11473
    // Defaults
11474
0
    ImGuiScrollFlags in_flags = flags;
11475
0
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
11476
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
11477
0
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
11478
0
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
11479
11480
0
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
11481
0
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
11482
0
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11483
0
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
11484
11485
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
11486
0
    {
11487
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
11488
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
11489
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
11490
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
11491
0
    }
11492
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
11493
0
    {
11494
0
        if (can_be_fully_visible_x)
11495
0
            SetScrollFromPosX(window, ImTrunc((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
11496
0
        else
11497
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
11498
0
    }
11499
11500
0
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
11501
0
    {
11502
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
11503
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
11504
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
11505
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
11506
0
    }
11507
0
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
11508
0
    {
11509
0
        if (can_be_fully_visible_y)
11510
0
            SetScrollFromPosY(window, ImTrunc((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
11511
0
        else
11512
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
11513
0
    }
11514
11515
0
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11516
0
    ImVec2 delta_scroll = next_scroll - window->Scroll;
11517
11518
    // Also scroll parent window to keep us into view if necessary
11519
0
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
11520
0
    {
11521
        // FIXME-SCROLL: May be an option?
11522
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
11523
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
11524
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
11525
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
11526
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
11527
0
    }
11528
11529
0
    return delta_scroll;
11530
0
}
11531
11532
float ImGui::GetScrollX()
11533
31.6k
{
11534
31.6k
    ImGuiWindow* window = GImGui->CurrentWindow;
11535
31.6k
    return window->Scroll.x;
11536
31.6k
}
11537
11538
float ImGui::GetScrollY()
11539
31.6k
{
11540
31.6k
    ImGuiWindow* window = GImGui->CurrentWindow;
11541
31.6k
    return window->Scroll.y;
11542
31.6k
}
11543
11544
float ImGui::GetScrollMaxX()
11545
0
{
11546
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11547
0
    return window->ScrollMax.x;
11548
0
}
11549
11550
float ImGui::GetScrollMaxY()
11551
0
{
11552
0
    ImGuiWindow* window = GImGui->CurrentWindow;
11553
0
    return window->ScrollMax.y;
11554
0
}
11555
11556
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
11557
5.87k
{
11558
5.87k
    window->ScrollTarget.x = scroll_x;
11559
5.87k
    window->ScrollTargetCenterRatio.x = 0.0f;
11560
5.87k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11561
5.87k
}
11562
11563
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
11564
4.97k
{
11565
4.97k
    window->ScrollTarget.y = scroll_y;
11566
4.97k
    window->ScrollTargetCenterRatio.y = 0.0f;
11567
4.97k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11568
4.97k
}
11569
11570
void ImGui::SetScrollX(float scroll_x)
11571
5.80k
{
11572
5.80k
    ImGuiContext& g = *GImGui;
11573
5.80k
    SetScrollX(g.CurrentWindow, scroll_x);
11574
5.80k
}
11575
11576
void ImGui::SetScrollY(float scroll_y)
11577
4.90k
{
11578
4.90k
    ImGuiContext& g = *GImGui;
11579
4.90k
    SetScrollY(g.CurrentWindow, scroll_y);
11580
4.90k
}
11581
11582
// Note that a local position will vary depending on initial scroll value,
11583
// This is a little bit confusing so bear with us:
11584
//  - local_pos = (absolution_pos - window->Pos)
11585
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
11586
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
11587
//  - They mostly exist because of legacy API.
11588
// Following the rules above, when trying to work with scrolling code, consider that:
11589
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
11590
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
11591
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
11592
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
11593
0
{
11594
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
11595
0
    window->ScrollTarget.x = IM_TRUNC(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
11596
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
11597
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
11598
0
}
11599
11600
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
11601
0
{
11602
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
11603
0
    window->ScrollTarget.y = IM_TRUNC(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
11604
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
11605
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
11606
0
}
11607
11608
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
11609
0
{
11610
0
    ImGuiContext& g = *GImGui;
11611
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
11612
0
}
11613
11614
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
11615
0
{
11616
0
    ImGuiContext& g = *GImGui;
11617
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
11618
0
}
11619
11620
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
11621
void ImGui::SetScrollHereX(float center_x_ratio)
11622
0
{
11623
0
    ImGuiContext& g = *GImGui;
11624
0
    ImGuiWindow* window = g.CurrentWindow;
11625
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
11626
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
11627
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
11628
11629
    // Tweak: snap on edges when aiming at an item very close to the edge
11630
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
11631
0
}
11632
11633
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
11634
void ImGui::SetScrollHereY(float center_y_ratio)
11635
0
{
11636
0
    ImGuiContext& g = *GImGui;
11637
0
    ImGuiWindow* window = g.CurrentWindow;
11638
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
11639
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
11640
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
11641
11642
    // Tweak: snap on edges when aiming at an item very close to the edge
11643
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
11644
0
}
11645
11646
//-----------------------------------------------------------------------------
11647
// [SECTION] TOOLTIPS
11648
//-----------------------------------------------------------------------------
11649
11650
bool ImGui::BeginTooltip()
11651
3
{
11652
3
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11653
3
}
11654
11655
bool ImGui::BeginItemTooltip()
11656
0
{
11657
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11658
0
        return false;
11659
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
11660
0
}
11661
11662
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
11663
3
{
11664
3
    ImGuiContext& g = *GImGui;
11665
11666
3
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
11667
0
    {
11668
        // Drag and Drop tooltips are positioning differently than other tooltips:
11669
        // - offset visibility to increase visibility around mouse.
11670
        // - never clamp within outer viewport boundary.
11671
        // We call SetNextWindowPos() to enforce position and disable clamping.
11672
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
11673
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
11674
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
11675
0
        SetNextWindowPos(tooltip_pos);
11676
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
11677
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
11678
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
11679
0
    }
11680
11681
3
    char window_name[16];
11682
3
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
11683
3
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
11684
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
11685
0
            if (window->Active)
11686
0
            {
11687
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
11688
0
                SetWindowHiddenAndSkipItemsForCurrentFrame(window);
11689
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
11690
0
            }
11691
3
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
11692
3
    Begin(window_name, NULL, flags | extra_window_flags);
11693
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
11694
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
11695
    //if (!ret)
11696
    //    End();
11697
    //return ret;
11698
3
    return true;
11699
3
}
11700
11701
void ImGui::EndTooltip()
11702
3
{
11703
3
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
11704
3
    End();
11705
3
}
11706
11707
void ImGui::SetTooltip(const char* fmt, ...)
11708
0
{
11709
0
    va_list args;
11710
0
    va_start(args, fmt);
11711
0
    SetTooltipV(fmt, args);
11712
0
    va_end(args);
11713
0
}
11714
11715
void ImGui::SetTooltipV(const char* fmt, va_list args)
11716
0
{
11717
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
11718
0
        return;
11719
0
    TextV(fmt, args);
11720
0
    EndTooltip();
11721
0
}
11722
11723
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
11724
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
11725
void ImGui::SetItemTooltip(const char* fmt, ...)
11726
0
{
11727
0
    va_list args;
11728
0
    va_start(args, fmt);
11729
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11730
0
        SetTooltipV(fmt, args);
11731
0
    va_end(args);
11732
0
}
11733
11734
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
11735
0
{
11736
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
11737
0
        SetTooltipV(fmt, args);
11738
0
}
11739
11740
11741
//-----------------------------------------------------------------------------
11742
// [SECTION] POPUPS
11743
//-----------------------------------------------------------------------------
11744
11745
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
11746
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
11747
0
{
11748
0
    ImGuiContext& g = *GImGui;
11749
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
11750
0
    {
11751
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
11752
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
11753
0
        IM_ASSERT(id == 0);
11754
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11755
0
            return g.OpenPopupStack.Size > 0;
11756
0
        else
11757
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
11758
0
    }
11759
0
    else
11760
0
    {
11761
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
11762
0
        {
11763
            // Return true if the popup is open anywhere in the popup stack
11764
0
            for (ImGuiPopupData& popup_data : g.OpenPopupStack)
11765
0
                if (popup_data.PopupId == id)
11766
0
                    return true;
11767
0
            return false;
11768
0
        }
11769
0
        else
11770
0
        {
11771
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
11772
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
11773
0
        }
11774
0
    }
11775
0
}
11776
11777
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
11778
0
{
11779
0
    ImGuiContext& g = *GImGui;
11780
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
11781
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
11782
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
11783
0
    return IsPopupOpen(id, popup_flags);
11784
0
}
11785
11786
// Also see FindBlockingModal(NULL)
11787
ImGuiWindow* ImGui::GetTopMostPopupModal()
11788
241k
{
11789
241k
    ImGuiContext& g = *GImGui;
11790
241k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11791
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11792
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
11793
0
                return popup;
11794
241k
    return NULL;
11795
241k
}
11796
11797
// See Demo->Stacked Modal to confirm what this is for.
11798
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
11799
80.5k
{
11800
80.5k
    ImGuiContext& g = *GImGui;
11801
80.5k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
11802
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
11803
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
11804
0
                return popup;
11805
80.5k
    return NULL;
11806
80.5k
}
11807
11808
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
11809
0
{
11810
0
    ImGuiContext& g = *GImGui;
11811
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11812
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
11813
0
    OpenPopupEx(id, popup_flags);
11814
0
}
11815
11816
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
11817
0
{
11818
0
    OpenPopupEx(id, popup_flags);
11819
0
}
11820
11821
// Mark popup as open (toggle toward open state).
11822
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
11823
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
11824
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
11825
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
11826
0
{
11827
0
    ImGuiContext& g = *GImGui;
11828
0
    ImGuiWindow* parent_window = g.CurrentWindow;
11829
0
    const int current_stack_size = g.BeginPopupStack.Size;
11830
11831
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
11832
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
11833
0
            return;
11834
11835
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
11836
0
    popup_ref.PopupId = id;
11837
0
    popup_ref.Window = NULL;
11838
0
    popup_ref.RestoreNavWindow = g.NavWindow;           // When popup closes focus may be restored to NavWindow (depend on window type).
11839
0
    popup_ref.OpenFrameCount = g.FrameCount;
11840
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
11841
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
11842
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
11843
11844
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
11845
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
11846
0
    {
11847
0
        g.OpenPopupStack.push_back(popup_ref);
11848
0
    }
11849
0
    else
11850
0
    {
11851
        // Gently handle the user mistakenly calling OpenPopup() every frames: it is likely a programming mistake!
11852
        // However, if we were to run the regular code path, the ui would become completely unusable because the popup will always be
11853
        // in hidden-while-calculating-size state _while_ claiming focus. Which is extremely confusing situation for the programmer.
11854
        // Instead, for successive frames calls to OpenPopup(), we silently avoid reopening even if ImGuiPopupFlags_NoReopen is not specified.
11855
0
        bool keep_existing = false;
11856
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id)
11857
0
            if ((g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) || (popup_flags & ImGuiPopupFlags_NoReopen))
11858
0
                keep_existing = true;
11859
0
        if (keep_existing)
11860
0
        {
11861
            // No reopen
11862
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11863
0
        }
11864
0
        else
11865
0
        {
11866
            // Reopen: close child popups if any, then flag popup for open/reopen (set position, focus, init navigation)
11867
0
            ClosePopupToLevel(current_stack_size, true);
11868
0
            g.OpenPopupStack.push_back(popup_ref);
11869
0
        }
11870
11871
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11872
        // This is equivalent to what ClosePopupToLevel() does.
11873
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11874
        //    FocusWindow(parent_window);
11875
0
    }
11876
0
}
11877
11878
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11879
// This function closes any popups that are over 'ref_window'.
11880
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11881
7.05k
{
11882
7.05k
    ImGuiContext& g = *GImGui;
11883
7.05k
    if (g.OpenPopupStack.Size == 0)
11884
7.05k
        return;
11885
11886
    // Don't close our own child popup windows.
11887
    //IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window ? ref_window->Name : "<NULL>", restore_focus_to_window_under_popup);
11888
0
    int popup_count_to_keep = 0;
11889
0
    if (ref_window)
11890
0
    {
11891
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11892
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11893
0
        {
11894
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11895
0
            if (!popup.Window)
11896
0
                continue;
11897
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11898
11899
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11900
            // - Clicking/Focusing Window2 won't close Popup1:
11901
            //     Window -> Popup1 -> Window2(Ref)
11902
            // - Clicking/focusing Popup1 will close Popup2 and Popup3:
11903
            //     Window -> Popup1(Ref) -> Popup2 -> Popup3
11904
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11905
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11906
            // We step through every popup from bottom to top to validate their position relative to reference window.
11907
0
            bool ref_window_is_descendent_of_popup = false;
11908
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11909
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11910
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11911
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11912
0
                    {
11913
0
                        ref_window_is_descendent_of_popup = true;
11914
0
                        break;
11915
0
                    }
11916
0
            if (!ref_window_is_descendent_of_popup)
11917
0
                break;
11918
0
        }
11919
0
    }
11920
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11921
0
    {
11922
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11923
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11924
0
    }
11925
0
}
11926
11927
void ImGui::ClosePopupsExceptModals()
11928
0
{
11929
0
    ImGuiContext& g = *GImGui;
11930
11931
0
    int popup_count_to_keep;
11932
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11933
0
    {
11934
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11935
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11936
0
            break;
11937
0
    }
11938
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11939
0
        ClosePopupToLevel(popup_count_to_keep, true);
11940
0
}
11941
11942
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11943
0
{
11944
0
    ImGuiContext& g = *GImGui;
11945
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup);
11946
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11947
11948
    // Trim open popup stack
11949
0
    ImGuiPopupData prev_popup = g.OpenPopupStack[remaining];
11950
0
    g.OpenPopupStack.resize(remaining);
11951
11952
    // Restore focus (unless popup window was not yet submitted, and didn't have a chance to take focus anyhow. See #7325 for an edge case)
11953
0
    if (restore_focus_to_window_under_popup && prev_popup.Window)
11954
0
    {
11955
0
        ImGuiWindow* popup_window = prev_popup.Window;
11956
0
        ImGuiWindow* focus_window = (popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : prev_popup.RestoreNavWindow;
11957
0
        if (focus_window && !focus_window->WasActive)
11958
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11959
0
        else
11960
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11961
0
    }
11962
0
}
11963
11964
// Close the popup we have begin-ed into.
11965
void ImGui::CloseCurrentPopup()
11966
0
{
11967
0
    ImGuiContext& g = *GImGui;
11968
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11969
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11970
0
        return;
11971
11972
    // Closing a menu closes its top-most parent popup (unless a modal)
11973
0
    while (popup_idx > 0)
11974
0
    {
11975
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11976
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11977
0
        bool close_parent = false;
11978
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11979
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11980
0
                close_parent = true;
11981
0
        if (!close_parent)
11982
0
            break;
11983
0
        popup_idx--;
11984
0
    }
11985
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11986
0
    ClosePopupToLevel(popup_idx, true);
11987
11988
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11989
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11990
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11991
0
    if (ImGuiWindow* window = g.NavWindow)
11992
0
        window->DC.NavHideHighlightOneFrame = true;
11993
0
}
11994
11995
// Attention! BeginPopup() adds default flags when calling BeginPopupEx()!
11996
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_window_flags)
11997
0
{
11998
0
    ImGuiContext& g = *GImGui;
11999
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12000
0
    {
12001
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12002
0
        return false;
12003
0
    }
12004
12005
0
    char name[20];
12006
0
    if (extra_window_flags & ImGuiWindowFlags_ChildMenu)
12007
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuDepth); // Recycle windows based on depth
12008
0
    else
12009
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
12010
12011
0
    bool is_open = Begin(name, NULL, extra_window_flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking);
12012
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
12013
0
        EndPopup();
12014
12015
    //g.CurrentWindow->FocusRouteParentWindow = g.CurrentWindow->ParentWindowInBeginStack;
12016
12017
0
    return is_open;
12018
0
}
12019
12020
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
12021
0
{
12022
0
    ImGuiContext& g = *GImGui;
12023
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
12024
0
    {
12025
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12026
0
        return false;
12027
0
    }
12028
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
12029
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
12030
0
    return BeginPopupEx(id, flags);
12031
0
}
12032
12033
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
12034
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup).
12035
// - *p_open set back to false in BeginPopupModal() when popup is not open.
12036
// - if you set *p_open to false before calling BeginPopupModal(), it will close the popup.
12037
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
12038
0
{
12039
0
    ImGuiContext& g = *GImGui;
12040
0
    ImGuiWindow* window = g.CurrentWindow;
12041
0
    const ImGuiID id = window->GetID(name);
12042
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
12043
0
    {
12044
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
12045
0
        if (p_open && *p_open)
12046
0
            *p_open = false;
12047
0
        return false;
12048
0
    }
12049
12050
    // Center modal windows by default for increased visibility
12051
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
12052
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
12053
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
12054
0
    {
12055
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
12056
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
12057
0
    }
12058
12059
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
12060
0
    const bool is_open = Begin(name, p_open, flags);
12061
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
12062
0
    {
12063
0
        EndPopup();
12064
0
        if (is_open)
12065
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
12066
0
        return false;
12067
0
    }
12068
0
    return is_open;
12069
0
}
12070
12071
void ImGui::EndPopup()
12072
0
{
12073
0
    ImGuiContext& g = *GImGui;
12074
0
    ImGuiWindow* window = g.CurrentWindow;
12075
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
12076
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
12077
12078
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
12079
0
    if (g.NavWindow == window)
12080
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
12081
12082
    // Child-popups don't need to be laid out
12083
0
    IM_ASSERT(g.WithinEndChild == false);
12084
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
12085
0
        g.WithinEndChild = true;
12086
0
    End();
12087
0
    g.WithinEndChild = false;
12088
0
}
12089
12090
// Helper to open a popup if mouse button is released over the item
12091
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
12092
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
12093
0
{
12094
0
    ImGuiContext& g = *GImGui;
12095
0
    ImGuiWindow* window = g.CurrentWindow;
12096
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12097
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12098
0
    {
12099
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12100
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12101
0
        OpenPopupEx(id, popup_flags);
12102
0
    }
12103
0
}
12104
12105
// This is a helper to handle the simplest case of associating one named popup to one given widget.
12106
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
12107
// - To create a popup with a specific identifier, pass it in str_id.
12108
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
12109
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
12110
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
12111
//   This is essentially the same as:
12112
//       id = str_id ? GetID(str_id) : GetItemID();
12113
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
12114
//       return BeginPopup(id);
12115
//   Which is essentially the same as:
12116
//       id = str_id ? GetID(str_id) : GetItemID();
12117
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
12118
//           OpenPopup(id);
12119
//       return BeginPopup(id);
12120
//   The main difference being that this is tweaked to avoid computing the ID twice.
12121
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
12122
0
{
12123
0
    ImGuiContext& g = *GImGui;
12124
0
    ImGuiWindow* window = g.CurrentWindow;
12125
0
    if (window->SkipItems)
12126
0
        return false;
12127
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
12128
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
12129
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12130
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12131
0
        OpenPopupEx(id, popup_flags);
12132
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12133
0
}
12134
12135
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
12136
0
{
12137
0
    ImGuiContext& g = *GImGui;
12138
0
    ImGuiWindow* window = g.CurrentWindow;
12139
0
    if (!str_id)
12140
0
        str_id = "window_context";
12141
0
    ImGuiID id = window->GetID(str_id);
12142
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12143
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
12144
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
12145
0
            OpenPopupEx(id, popup_flags);
12146
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12147
0
}
12148
12149
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
12150
0
{
12151
0
    ImGuiContext& g = *GImGui;
12152
0
    ImGuiWindow* window = g.CurrentWindow;
12153
0
    if (!str_id)
12154
0
        str_id = "void_context";
12155
0
    ImGuiID id = window->GetID(str_id);
12156
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
12157
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
12158
0
        if (GetTopMostPopupModal() == NULL)
12159
0
            OpenPopupEx(id, popup_flags);
12160
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
12161
0
}
12162
12163
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
12164
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
12165
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
12166
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
12167
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
12168
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
12169
3
{
12170
3
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
12171
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
12172
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
12173
12174
    // Combo Box policy (we want a connecting edge)
12175
3
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
12176
0
    {
12177
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
12178
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12179
0
        {
12180
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12181
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12182
0
                continue;
12183
0
            ImVec2 pos;
12184
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
12185
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
12186
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
12187
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
12188
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
12189
0
                continue;
12190
0
            *last_dir = dir;
12191
0
            return pos;
12192
0
        }
12193
0
    }
12194
12195
    // Tooltip and Default popup policy
12196
    // (Always first try the direction we used on the last frame, if any)
12197
3
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
12198
3
    {
12199
3
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
12200
3
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
12201
3
        {
12202
3
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
12203
3
            if (n != -1 && dir == *last_dir) // Already tried this direction?
12204
0
                continue;
12205
12206
3
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
12207
3
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
12208
12209
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
12210
3
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
12211
0
                continue;
12212
3
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
12213
0
                continue;
12214
12215
3
            ImVec2 pos;
12216
3
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
12217
3
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
12218
12219
            // Clamp top-left corner of popup
12220
3
            pos.x = ImMax(pos.x, r_outer.Min.x);
12221
3
            pos.y = ImMax(pos.y, r_outer.Min.y);
12222
12223
3
            *last_dir = dir;
12224
3
            return pos;
12225
3
        }
12226
3
    }
12227
12228
    // Fallback when not enough room:
12229
0
    *last_dir = ImGuiDir_None;
12230
12231
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
12232
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
12233
0
        return ref_pos + ImVec2(2, 2);
12234
12235
    // Otherwise try to keep within display
12236
0
    ImVec2 pos = ref_pos;
12237
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
12238
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
12239
0
    return pos;
12240
0
}
12241
12242
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
12243
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
12244
3
{
12245
3
    ImGuiContext& g = *GImGui;
12246
3
    ImRect r_screen;
12247
3
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
12248
0
    {
12249
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
12250
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
12251
0
        r_screen.Min = monitor.WorkPos;
12252
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
12253
0
    }
12254
3
    else
12255
3
    {
12256
        // Use the full viewport area (not work area) for popups
12257
3
        r_screen = window->Viewport->GetMainRect();
12258
3
    }
12259
3
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
12260
3
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
12261
3
    return r_screen;
12262
3
}
12263
12264
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
12265
3
{
12266
3
    ImGuiContext& g = *GImGui;
12267
12268
3
    ImRect r_outer = GetPopupAllowedExtentRect(window);
12269
3
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
12270
0
    {
12271
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
12272
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
12273
0
        ImGuiWindow* parent_window = window->ParentWindow;
12274
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
12275
0
        ImRect r_avoid;
12276
0
        if (parent_window->DC.MenuBarAppending)
12277
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
12278
0
        else
12279
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
12280
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
12281
0
    }
12282
3
    if (window->Flags & ImGuiWindowFlags_Popup)
12283
0
    {
12284
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
12285
0
    }
12286
3
    if (window->Flags & ImGuiWindowFlags_Tooltip)
12287
3
    {
12288
        // Position tooltip (always follows mouse + clamp within outer boundaries)
12289
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
12290
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
12291
3
        IM_ASSERT(g.CurrentWindow == window);
12292
3
        const float scale = g.Style.MouseCursorScale;
12293
3
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
12294
3
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
12295
3
        ImRect r_avoid;
12296
3
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
12297
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
12298
3
        else
12299
3
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
12300
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
12301
3
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
12302
3
    }
12303
0
    IM_ASSERT(0);
12304
0
    return window->Pos;
12305
3
}
12306
12307
//-----------------------------------------------------------------------------
12308
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
12309
//-----------------------------------------------------------------------------
12310
12311
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
12312
// In our terminology those should be interchangeable, yet right now this is super confusing.
12313
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
12314
12315
void ImGui::SetNavWindow(ImGuiWindow* window)
12316
6.85k
{
12317
6.85k
    ImGuiContext& g = *GImGui;
12318
6.85k
    if (g.NavWindow != window)
12319
6.85k
    {
12320
6.85k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
12321
6.85k
        g.NavWindow = window;
12322
6.85k
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12323
6.85k
    }
12324
6.85k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12325
6.85k
    NavUpdateAnyRequestFlag();
12326
6.85k
}
12327
12328
void ImGui::NavHighlightActivated(ImGuiID id)
12329
4
{
12330
4
    ImGuiContext& g = *GImGui;
12331
4
    g.NavHighlightActivatedId = id;
12332
4
    g.NavHighlightActivatedTimer = NAV_ACTIVATE_HIGHLIGHT_TIMER;
12333
4
}
12334
12335
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
12336
1.16k
{
12337
1.16k
    ImGuiContext& g = *GImGui;
12338
1.16k
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
12339
1.16k
}
12340
12341
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
12342
243
{
12343
243
    ImGuiContext& g = *GImGui;
12344
243
    IM_ASSERT(g.NavWindow != NULL);
12345
243
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
12346
243
    g.NavId = id;
12347
243
    g.NavLayer = nav_layer;
12348
243
    SetNavFocusScope(focus_scope_id);
12349
243
    g.NavWindow->NavLastIds[nav_layer] = id;
12350
243
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
12351
12352
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12353
243
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12354
243
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12355
243
}
12356
12357
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
12358
4
{
12359
4
    ImGuiContext& g = *GImGui;
12360
4
    IM_ASSERT(id != 0);
12361
12362
4
    if (g.NavWindow != window)
12363
4
       SetNavWindow(window);
12364
12365
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
12366
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
12367
4
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
12368
4
    g.NavId = id;
12369
4
    g.NavLayer = nav_layer;
12370
4
    SetNavFocusScope(g.CurrentFocusScopeId);
12371
4
    window->NavLastIds[nav_layer] = id;
12372
4
    if (g.LastItemData.ID == id)
12373
4
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12374
12375
4
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
12376
4
        g.NavDisableMouseHover = true;
12377
0
    else
12378
0
        g.NavDisableHighlight = true;
12379
12380
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
12381
4
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12382
4
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12383
4
}
12384
12385
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
12386
0
{
12387
0
    if (ImFabs(dx) > ImFabs(dy))
12388
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
12389
0
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
12390
0
}
12391
12392
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
12393
0
{
12394
0
    if (cand_max < curr_min)
12395
0
        return cand_max - curr_min;
12396
0
    if (curr_max < cand_min)
12397
0
        return cand_min - curr_max;
12398
0
    return 0.0f;
12399
0
}
12400
12401
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
12402
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
12403
0
{
12404
0
    ImGuiContext& g = *GImGui;
12405
0
    ImGuiWindow* window = g.CurrentWindow;
12406
0
    if (g.NavLayer != window->DC.NavLayerCurrent)
12407
0
        return false;
12408
12409
    // FIXME: Those are not good variables names
12410
0
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
12411
0
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
12412
0
    g.NavScoringDebugCount++;
12413
12414
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
12415
0
    if (window->ParentWindow == g.NavWindow)
12416
0
    {
12417
0
        IM_ASSERT((window->ChildFlags | g.NavWindow->ChildFlags) & ImGuiChildFlags_NavFlattened);
12418
0
        if (!window->ClipRect.Overlaps(cand))
12419
0
            return false;
12420
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
12421
0
    }
12422
12423
    // Compute distance between boxes
12424
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
12425
0
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
12426
0
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
12427
0
    if (dby != 0.0f && dbx != 0.0f)
12428
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
12429
0
    float dist_box = ImFabs(dbx) + ImFabs(dby);
12430
12431
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
12432
0
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
12433
0
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
12434
0
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
12435
12436
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
12437
0
    ImGuiDir quadrant;
12438
0
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
12439
0
    if (dbx != 0.0f || dby != 0.0f)
12440
0
    {
12441
        // For non-overlapping boxes, use distance between boxes
12442
        // FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y
12443
        // One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir_Right, pressing Left to navigate from Close to Collapse tends to fail.
12444
        // Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty.
12445
0
        dax = dbx;
12446
0
        day = dby;
12447
0
        dist_axial = dist_box;
12448
0
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
12449
0
    }
12450
0
    else if (dcx != 0.0f || dcy != 0.0f)
12451
0
    {
12452
        // For overlapping boxes with different centers, use distance between centers
12453
0
        dax = dcx;
12454
0
        day = dcy;
12455
0
        dist_axial = dist_center;
12456
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
12457
0
    }
12458
0
    else
12459
0
    {
12460
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
12461
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
12462
0
    }
12463
12464
0
    const ImGuiDir move_dir = g.NavMoveDir;
12465
#if IMGUI_DEBUG_NAV_SCORING
12466
    char buf[200];
12467
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
12468
    {
12469
        if (quadrant == move_dir)
12470
        {
12471
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
12472
            ImDrawList* draw_list = GetForegroundDrawList(window);
12473
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
12474
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
12475
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
12476
        }
12477
    }
12478
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
12479
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
12480
    if (debug_hovering || debug_tty)
12481
    {
12482
        ImFormatString(buf, IM_ARRAYSIZE(buf),
12483
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
12484
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
12485
        if (debug_hovering)
12486
        {
12487
            ImDrawList* draw_list = GetForegroundDrawList(window);
12488
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
12489
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
12490
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
12491
            draw_list->AddText(cand.Max, ~0U, buf);
12492
        }
12493
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
12494
    }
12495
#endif
12496
12497
    // Is it in the quadrant we're interested in moving to?
12498
0
    bool new_best = false;
12499
0
    if (quadrant == move_dir)
12500
0
    {
12501
        // Does it beat the current best candidate?
12502
0
        if (dist_box < result->DistBox)
12503
0
        {
12504
0
            result->DistBox = dist_box;
12505
0
            result->DistCenter = dist_center;
12506
0
            return true;
12507
0
        }
12508
0
        if (dist_box == result->DistBox)
12509
0
        {
12510
            // Try using distance between center points to break ties
12511
0
            if (dist_center < result->DistCenter)
12512
0
            {
12513
0
                result->DistCenter = dist_center;
12514
0
                new_best = true;
12515
0
            }
12516
0
            else if (dist_center == result->DistCenter)
12517
0
            {
12518
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
12519
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
12520
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
12521
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
12522
0
                    new_best = true;
12523
0
            }
12524
0
        }
12525
0
    }
12526
12527
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
12528
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
12529
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
12530
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
12531
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
12532
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
12533
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
12534
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
12535
0
            {
12536
0
                result->DistAxial = dist_axial;
12537
0
                new_best = true;
12538
0
            }
12539
12540
0
    return new_best;
12541
0
}
12542
12543
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
12544
105
{
12545
105
    ImGuiContext& g = *GImGui;
12546
105
    ImGuiWindow* window = g.CurrentWindow;
12547
105
    result->Window = window;
12548
105
    result->ID = g.LastItemData.ID;
12549
105
    result->FocusScopeId = g.CurrentFocusScopeId;
12550
105
    result->InFlags = g.LastItemData.InFlags;
12551
105
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
12552
105
    if (result->InFlags & ImGuiItemFlags_HasSelectionUserData)
12553
0
    {
12554
0
        IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12555
0
        result->SelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12556
0
    }
12557
105
}
12558
12559
// True when current work location may be scrolled horizontally when moving left / right.
12560
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
12561
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
12562
292k
{
12563
292k
    ImGuiContext& g = *GImGui;
12564
292k
    ImGuiWindow* window = g.CurrentWindow;
12565
292k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
12566
292k
}
12567
12568
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
12569
// This is called after LastItemData is set, but NextItemData is also still valid.
12570
static void ImGui::NavProcessItem()
12571
1.00k
{
12572
1.00k
    ImGuiContext& g = *GImGui;
12573
1.00k
    ImGuiWindow* window = g.CurrentWindow;
12574
1.00k
    const ImGuiID id = g.LastItemData.ID;
12575
1.00k
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
12576
12577
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
12578
1.00k
    if (window->DC.NavIsScrollPushableX == false)
12579
0
    {
12580
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12581
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
12582
0
    }
12583
1.00k
    const ImRect nav_bb = g.LastItemData.NavRect;
12584
12585
    // Process Init Request
12586
1.00k
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
12587
105
    {
12588
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
12589
105
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
12590
105
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
12591
105
        {
12592
105
            NavApplyItemToResult(&g.NavInitResult);
12593
105
        }
12594
105
        if (candidate_for_nav_default_focus)
12595
0
        {
12596
0
            g.NavInitRequest = false; // Found a match, clear request
12597
0
            NavUpdateAnyRequestFlag();
12598
0
        }
12599
105
    }
12600
12601
    // Process Move Request (scoring for navigation)
12602
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
12603
1.00k
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
12604
0
    {
12605
0
        if ((g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi) || (window->Flags & ImGuiWindowFlags_NoNavInputs) == 0)
12606
0
        {
12607
0
            const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
12608
0
            if (is_tabbing)
12609
0
            {
12610
0
                NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
12611
0
            }
12612
0
            else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
12613
0
            {
12614
0
                ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
12615
0
                if (NavScoreItem(result))
12616
0
                    NavApplyItemToResult(result);
12617
12618
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
12619
0
                const float VISIBLE_RATIO = 0.70f;
12620
0
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
12621
0
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
12622
0
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
12623
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
12624
0
            }
12625
0
        }
12626
0
    }
12627
12628
    // Update information for currently focused/navigated item
12629
1.00k
    if (g.NavId == id)
12630
848
    {
12631
848
        if (g.NavWindow != window)
12632
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
12633
848
        g.NavLayer = window->DC.NavLayerCurrent;
12634
848
        SetNavFocusScope(g.CurrentFocusScopeId); // Will set g.NavFocusScopeId AND store g.NavFocusScopePath
12635
848
        g.NavFocusScopeId = g.CurrentFocusScopeId;
12636
848
        g.NavIdIsAlive = true;
12637
848
        if (g.LastItemData.InFlags & ImGuiItemFlags_HasSelectionUserData)
12638
0
        {
12639
0
            IM_ASSERT(g.NextItemData.SelectionUserData != ImGuiSelectionUserData_Invalid);
12640
0
            g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData; // INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData.
12641
0
        }
12642
848
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
12643
848
    }
12644
1.00k
}
12645
12646
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
12647
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
12648
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
12649
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
12650
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
12651
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
12652
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
12653
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
12654
0
{
12655
0
    ImGuiContext& g = *GImGui;
12656
12657
0
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
12658
0
    {
12659
0
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
12660
0
            return;
12661
0
        if (g.NavFocusScopeId != g.CurrentFocusScopeId)
12662
0
            return;
12663
0
    }
12664
12665
    // - Can always land on an item when using API call.
12666
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
12667
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
12668
0
    bool can_stop;
12669
0
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
12670
0
        can_stop = true;
12671
0
    else
12672
0
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
12673
12674
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
12675
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
12676
0
    if (g.NavTabbingDir == +1)
12677
0
    {
12678
        // Tab Forward or SetKeyboardFocusHere() with >= 0
12679
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
12680
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12681
0
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
12682
0
            NavMoveRequestResolveWithLastItem(result);
12683
0
        else if (g.NavId == id)
12684
0
            g.NavTabbingCounter = 1;
12685
0
    }
12686
0
    else if (g.NavTabbingDir == -1)
12687
0
    {
12688
        // Tab Backward
12689
0
        if (g.NavId == id)
12690
0
        {
12691
0
            if (result->ID)
12692
0
            {
12693
0
                g.NavMoveScoringItems = false;
12694
0
                NavUpdateAnyRequestFlag();
12695
0
            }
12696
0
        }
12697
0
        else if (can_stop)
12698
0
        {
12699
            // Keep applying until reaching NavId
12700
0
            NavApplyItemToResult(result);
12701
0
        }
12702
0
    }
12703
0
    else if (g.NavTabbingDir == 0)
12704
0
    {
12705
0
        if (can_stop && g.NavId == id)
12706
0
            NavMoveRequestResolveWithLastItem(result);
12707
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
12708
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
12709
0
    }
12710
0
}
12711
12712
bool ImGui::NavMoveRequestButNoResultYet()
12713
20.0k
{
12714
20.0k
    ImGuiContext& g = *GImGui;
12715
20.0k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
12716
20.0k
}
12717
12718
// FIXME: ScoringRect is not set
12719
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12720
731
{
12721
731
    ImGuiContext& g = *GImGui;
12722
731
    IM_ASSERT(g.NavWindow != NULL);
12723
    //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name);
12724
12725
731
    if (move_flags & ImGuiNavMoveFlags_IsTabbing)
12726
592
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
12727
12728
731
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
12729
731
    g.NavMoveDir = move_dir;
12730
731
    g.NavMoveDirForDebug = move_dir;
12731
731
    g.NavMoveClipDir = clip_dir;
12732
731
    g.NavMoveFlags = move_flags;
12733
731
    g.NavMoveScrollFlags = scroll_flags;
12734
731
    g.NavMoveForwardToNextFrame = false;
12735
731
    g.NavMoveKeyMods = (move_flags & ImGuiNavMoveFlags_FocusApi) ? 0 : g.IO.KeyMods;
12736
731
    g.NavMoveResultLocal.Clear();
12737
731
    g.NavMoveResultLocalVisible.Clear();
12738
731
    g.NavMoveResultOther.Clear();
12739
731
    g.NavTabbingCounter = 0;
12740
731
    g.NavTabbingResultFirst.Clear();
12741
731
    NavUpdateAnyRequestFlag();
12742
731
}
12743
12744
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
12745
0
{
12746
0
    ImGuiContext& g = *GImGui;
12747
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
12748
0
    NavApplyItemToResult(result);
12749
0
    NavUpdateAnyRequestFlag();
12750
0
}
12751
12752
// Called by TreePop() to implement ImGuiTreeNodeFlags_NavLeftJumpsBackHere
12753
void ImGui::NavMoveRequestResolveWithPastTreeNode(ImGuiNavItemData* result, ImGuiTreeNodeStackData* tree_node_data)
12754
0
{
12755
0
    ImGuiContext& g = *GImGui;
12756
0
    g.NavMoveScoringItems = false;
12757
0
    g.LastItemData.ID = tree_node_data->ID;
12758
0
    g.LastItemData.InFlags = tree_node_data->InFlags & ~ImGuiItemFlags_HasSelectionUserData; // Losing SelectionUserData, recovered next-frame (cheaper).
12759
0
    g.LastItemData.NavRect = tree_node_data->NavRect;
12760
0
    NavApplyItemToResult(result); // Result this instead of implementing a NavApplyPastTreeNodeToResult()
12761
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12762
0
    NavUpdateAnyRequestFlag();
12763
0
}
12764
12765
void ImGui::NavMoveRequestCancel()
12766
4.89k
{
12767
4.89k
    ImGuiContext& g = *GImGui;
12768
4.89k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12769
4.89k
    NavUpdateAnyRequestFlag();
12770
4.89k
}
12771
12772
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
12773
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
12774
0
{
12775
0
    ImGuiContext& g = *GImGui;
12776
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
12777
0
    NavMoveRequestCancel();
12778
0
    g.NavMoveForwardToNextFrame = true;
12779
0
    g.NavMoveDir = move_dir;
12780
0
    g.NavMoveClipDir = clip_dir;
12781
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
12782
0
    g.NavMoveScrollFlags = scroll_flags;
12783
0
}
12784
12785
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
12786
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
12787
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
12788
0
{
12789
0
    ImGuiContext& g = *GImGui;
12790
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
12791
12792
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
12793
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
12794
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
12795
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
12796
0
}
12797
12798
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
12799
// This way we could find the last focused window among our children. It would be much less confusing this way?
12800
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
12801
17.5k
{
12802
17.5k
    ImGuiWindow* parent = nav_window;
12803
30.4k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12804
12.9k
        parent = parent->ParentWindow;
12805
17.5k
    if (parent && parent != nav_window)
12806
12.9k
        parent->NavLastChildNavWindow = nav_window;
12807
17.5k
}
12808
12809
// Restore the last focused child.
12810
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
12811
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
12812
107
{
12813
107
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
12814
103
        return window->NavLastChildNavWindow;
12815
4
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
12816
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
12817
0
            return tab->Window;
12818
4
    return window;
12819
4
}
12820
12821
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
12822
118
{
12823
118
    ImGuiContext& g = *GImGui;
12824
118
    if (layer == ImGuiNavLayer_Main)
12825
13
    {
12826
13
        ImGuiWindow* prev_nav_window = g.NavWindow;
12827
13
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
12828
13
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
12829
13
        if (prev_nav_window)
12830
13
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
12831
13
    }
12832
118
    ImGuiWindow* window = g.NavWindow;
12833
118
    if (window->NavLastIds[layer] != 0)
12834
13
    {
12835
13
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
12836
13
    }
12837
105
    else
12838
105
    {
12839
105
        g.NavLayer = layer;
12840
105
        NavInitWindow(window, true);
12841
105
    }
12842
118
}
12843
12844
void ImGui::NavRestoreHighlightAfterMove()
12845
274
{
12846
274
    ImGuiContext& g = *GImGui;
12847
274
    g.NavDisableHighlight = false;
12848
274
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
12849
274
}
12850
12851
static inline void ImGui::NavUpdateAnyRequestFlag()
12852
93.1k
{
12853
93.1k
    ImGuiContext& g = *GImGui;
12854
93.1k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
12855
93.1k
    if (g.NavAnyRequest)
12856
93.1k
        IM_ASSERT(g.NavWindow != NULL);
12857
93.1k
}
12858
12859
// This needs to be called before we submit any widget (aka in or before Begin)
12860
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
12861
107
{
12862
    // FIXME: ChildWindow test here is wrong for docking
12863
107
    ImGuiContext& g = *GImGui;
12864
107
    IM_ASSERT(window == g.NavWindow);
12865
12866
107
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
12867
0
    {
12868
0
        g.NavId = 0;
12869
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12870
0
        return;
12871
0
    }
12872
12873
107
    bool init_for_nav = false;
12874
107
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
12875
107
        init_for_nav = true;
12876
107
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
12877
107
    if (init_for_nav)
12878
107
    {
12879
107
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
12880
107
        g.NavInitRequest = true;
12881
107
        g.NavInitRequestFromMove = false;
12882
107
        g.NavInitResult.ID = 0;
12883
107
        NavUpdateAnyRequestFlag();
12884
107
    }
12885
0
    else
12886
0
    {
12887
0
        g.NavId = window->NavLastIds[0];
12888
0
        SetNavFocusScope(window->NavRootFocusScopeId);
12889
0
    }
12890
107
}
12891
12892
static ImVec2 ImGui::NavCalcPreferredRefPos()
12893
3
{
12894
3
    ImGuiContext& g = *GImGui;
12895
3
    ImGuiWindow* window = g.NavWindow;
12896
3
    const bool activated_shortcut = g.ActiveId != 0 && g.ActiveIdFromShortcut && g.ActiveId == g.LastItemData.ID;
12897
12898
    // Testing for !activated_shortcut here could in theory be removed if we decided that activating a remote shortcut altered one of the g.NavDisableXXX flag.
12899
3
    if ((g.NavDisableHighlight || !g.NavDisableMouseHover || !window) && !activated_shortcut)
12900
3
    {
12901
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
12902
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
12903
        // In theory we could move that +1.0f offset in OpenPopupEx()
12904
3
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
12905
3
        return ImVec2(p.x + 1.0f, p.y);
12906
3
    }
12907
0
    else
12908
0
    {
12909
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
12910
0
        ImRect ref_rect;
12911
0
        if (activated_shortcut)
12912
0
            ref_rect = g.LastItemData.NavRect;
12913
0
        else
12914
0
            ref_rect = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
12915
12916
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
12917
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12918
0
        {
12919
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12920
0
            ref_rect.Translate(window->Scroll - next_scroll);
12921
0
        }
12922
0
        ImVec2 pos = ImVec2(ref_rect.Min.x + ImMin(g.Style.FramePadding.x * 4, ref_rect.GetWidth()), ref_rect.Max.y - ImMin(g.Style.FramePadding.y, ref_rect.GetHeight()));
12923
0
        ImGuiViewport* viewport = window->Viewport;
12924
0
        return ImTrunc(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImTrunc() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12925
0
    }
12926
3
}
12927
12928
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12929
0
{
12930
0
    ImGuiContext& g = *GImGui;
12931
0
    float repeat_delay, repeat_rate;
12932
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12933
12934
0
    ImGuiKey key_less, key_more;
12935
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12936
0
    {
12937
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12938
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12939
0
    }
12940
0
    else
12941
0
    {
12942
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12943
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12944
0
    }
12945
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12946
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12947
0
        amount = 0.0f;
12948
0
    return amount;
12949
0
}
12950
12951
static void ImGui::NavUpdate()
12952
80.5k
{
12953
80.5k
    ImGuiContext& g = *GImGui;
12954
80.5k
    ImGuiIO& io = g.IO;
12955
12956
80.5k
    io.WantSetMousePos = false;
12957
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12958
12959
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12960
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12961
80.5k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12962
80.5k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12963
80.5k
    if (nav_gamepad_active)
12964
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12965
0
            if (IsKeyDown(key))
12966
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12967
80.5k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12968
80.5k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12969
80.5k
    if (nav_keyboard_active)
12970
80.5k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12971
563k
            if (IsKeyDown(key))
12972
12.6k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12973
12974
    // Process navigation init request (select first/default focus)
12975
80.5k
    g.NavJustMovedToId = 0;
12976
80.5k
    g.NavJustMovedToFocusScopeId = g.NavJustMovedFromFocusScopeId = 0;
12977
80.5k
    if (g.NavInitResult.ID != 0)
12978
105
        NavInitRequestApplyResult();
12979
80.5k
    g.NavInitRequest = false;
12980
80.5k
    g.NavInitRequestFromMove = false;
12981
80.5k
    g.NavInitResult.ID = 0;
12982
12983
    // Process navigation move request
12984
80.5k
    if (g.NavMoveSubmitted)
12985
666
        NavMoveRequestApplyResult();
12986
80.5k
    g.NavTabbingCounter = 0;
12987
80.5k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12988
12989
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12990
80.5k
    bool set_mouse_pos = false;
12991
80.5k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12992
112
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12993
112
            set_mouse_pos = true;
12994
80.5k
    g.NavMousePosDirty = false;
12995
80.5k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12996
12997
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12998
80.5k
    if (g.NavWindow)
12999
17.5k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
13000
80.5k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
13001
279
        g.NavWindow->NavLastChildNavWindow = NULL;
13002
13003
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
13004
80.5k
    NavUpdateWindowing();
13005
13006
    // Set output flags for user application
13007
80.5k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
13008
80.5k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
13009
13010
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
13011
80.5k
    NavUpdateCancelRequest();
13012
13013
    // Process manual activation request
13014
80.5k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
13015
80.5k
    g.NavActivateFlags = ImGuiActivateFlags_None;
13016
80.5k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13017
9.91k
    {
13018
9.91k
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate, ImGuiKeyOwner_NoOwner));
13019
9.91k
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, 0, ImGuiKeyOwner_NoOwner)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, 0, ImGuiKeyOwner_NoOwner)));
13020
9.91k
        const bool input_down = (nav_keyboard_active && (IsKeyDown(ImGuiKey_Enter, ImGuiKeyOwner_NoOwner) || IsKeyDown(ImGuiKey_KeypadEnter, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput, ImGuiKeyOwner_NoOwner));
13021
9.91k
        const bool input_pressed = input_down && ((nav_keyboard_active && (IsKeyPressed(ImGuiKey_Enter, 0, ImGuiKeyOwner_NoOwner) || IsKeyPressed(ImGuiKey_KeypadEnter, 0, ImGuiKeyOwner_NoOwner))) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, 0, ImGuiKeyOwner_NoOwner)));
13022
9.91k
        if (g.ActiveId == 0 && activate_pressed)
13023
3
        {
13024
3
            g.NavActivateId = g.NavId;
13025
3
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
13026
3
        }
13027
9.91k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
13028
1
        {
13029
1
            g.NavActivateId = g.NavId;
13030
1
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
13031
1
        }
13032
9.91k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
13033
83
            g.NavActivateDownId = g.NavId;
13034
9.91k
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
13035
4
        {
13036
4
            g.NavActivatePressedId = g.NavId;
13037
4
            NavHighlightActivated(g.NavId);
13038
4
        }
13039
9.91k
    }
13040
80.5k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
13041
0
        g.NavDisableHighlight = true;
13042
80.5k
    if (g.NavActivateId != 0)
13043
80.5k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
13044
13045
    // Highlight
13046
80.5k
    if (g.NavHighlightActivatedTimer > 0.0f)
13047
28
        g.NavHighlightActivatedTimer = ImMax(0.0f, g.NavHighlightActivatedTimer - io.DeltaTime);
13048
80.5k
    if (g.NavHighlightActivatedTimer == 0.0f)
13049
80.5k
        g.NavHighlightActivatedId = 0;
13050
13051
    // Process programmatic activation request
13052
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
13053
80.5k
    if (g.NavNextActivateId != 0)
13054
0
    {
13055
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
13056
0
        g.NavActivateFlags = g.NavNextActivateFlags;
13057
0
    }
13058
80.5k
    g.NavNextActivateId = 0;
13059
13060
    // Process move requests
13061
80.5k
    NavUpdateCreateMoveRequest();
13062
80.5k
    if (g.NavMoveDir == ImGuiDir_None)
13063
80.4k
        NavUpdateCreateTabbingRequest();
13064
80.5k
    NavUpdateAnyRequestFlag();
13065
80.5k
    g.NavIdIsAlive = false;
13066
13067
    // Scrolling
13068
80.5k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
13069
17.5k
    {
13070
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
13071
17.5k
        ImGuiWindow* window = g.NavWindow;
13072
17.5k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
13073
17.5k
        const ImGuiDir move_dir = g.NavMoveDir;
13074
17.5k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
13075
78
        {
13076
78
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
13077
70
                SetScrollX(window, ImTrunc(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
13078
78
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
13079
8
                SetScrollY(window, ImTrunc(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
13080
78
        }
13081
13082
        // *Normal* Manual scroll with LStick
13083
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
13084
17.5k
        if (nav_gamepad_active)
13085
0
        {
13086
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13087
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
13088
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
13089
0
                SetScrollX(window, ImTrunc(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
13090
0
            if (scroll_dir.y != 0.0f)
13091
0
                SetScrollY(window, ImTrunc(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
13092
0
        }
13093
17.5k
    }
13094
13095
    // Always prioritize mouse highlight if navigation is disabled
13096
80.5k
    if (!nav_keyboard_active && !nav_gamepad_active)
13097
0
    {
13098
0
        g.NavDisableHighlight = true;
13099
0
        g.NavDisableMouseHover = set_mouse_pos = false;
13100
0
    }
13101
13102
    // Update mouse position if requested
13103
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
13104
80.5k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
13105
0
        TeleportMousePos(NavCalcPreferredRefPos());
13106
13107
    // [DEBUG]
13108
80.5k
    g.NavScoringDebugCount = 0;
13109
#if IMGUI_DEBUG_NAV_RECTS
13110
    if (ImGuiWindow* debug_window = g.NavWindow)
13111
    {
13112
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
13113
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
13114
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
13115
    }
13116
#endif
13117
80.5k
}
13118
13119
void ImGui::NavInitRequestApplyResult()
13120
105
{
13121
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
13122
105
    ImGuiContext& g = *GImGui;
13123
105
    if (!g.NavWindow)
13124
29
        return;
13125
13126
76
    ImGuiNavItemData* result = &g.NavInitResult;
13127
76
    if (g.NavId != result->ID)
13128
52
    {
13129
52
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13130
52
        g.NavJustMovedToId = result->ID;
13131
52
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13132
52
        g.NavJustMovedToKeyMods = 0;
13133
52
        g.NavJustMovedToIsTabbing = false;
13134
52
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13135
52
    }
13136
13137
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
13138
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
13139
76
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13140
76
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13141
76
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
13142
76
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13143
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13144
76
    if (g.NavInitRequestFromMove)
13145
0
        NavRestoreHighlightAfterMove();
13146
76
}
13147
13148
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
13149
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
13150
139
{
13151
    // Bias initial rect
13152
139
    ImGuiContext& g = *GImGui;
13153
139
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
13154
13155
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
13156
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
13157
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
13158
139
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
13159
139
    {
13160
139
        if (preferred_pos_rel.x == FLT_MAX)
13161
119
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
13162
139
        if (preferred_pos_rel.y == FLT_MAX)
13163
17
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
13164
139
    }
13165
13166
    // Apply general bias on the other axis
13167
139
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
13168
22
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
13169
117
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
13170
117
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
13171
139
}
13172
13173
void ImGui::NavUpdateCreateMoveRequest()
13174
80.5k
{
13175
80.5k
    ImGuiContext& g = *GImGui;
13176
80.5k
    ImGuiIO& io = g.IO;
13177
80.5k
    ImGuiWindow* window = g.NavWindow;
13178
80.5k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13179
80.5k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13180
13181
80.5k
    if (g.NavMoveForwardToNextFrame && window != NULL)
13182
0
    {
13183
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
13184
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
13185
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
13186
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
13187
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
13188
0
    }
13189
80.5k
    else
13190
80.5k
    {
13191
        // Initiate directional inputs request
13192
80.5k
        g.NavMoveDir = ImGuiDir_None;
13193
80.5k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
13194
80.5k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
13195
80.5k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
13196
17.5k
        {
13197
17.5k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
13198
17.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Left; }
13199
17.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Right; }
13200
17.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Up; }
13201
17.5k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  repeat_mode, ImGuiKeyOwner_NoOwner)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  repeat_mode, ImGuiKeyOwner_NoOwner)))) { g.NavMoveDir = ImGuiDir_Down; }
13202
17.5k
        }
13203
80.5k
        g.NavMoveClipDir = g.NavMoveDir;
13204
80.5k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
13205
80.5k
    }
13206
13207
    // Update PageUp/PageDown/Home/End scroll
13208
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
13209
80.5k
    float scoring_rect_offset_y = 0.0f;
13210
80.5k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
13211
17.4k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
13212
80.5k
    if (scoring_rect_offset_y != 0.0f)
13213
7
    {
13214
7
        g.NavScoringNoClipRect = window->InnerRect;
13215
7
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
13216
7
    }
13217
13218
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
13219
#if IMGUI_DEBUG_NAV_SCORING
13220
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
13221
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
13222
    if (io.KeyCtrl)
13223
    {
13224
        if (g.NavMoveDir == ImGuiDir_None)
13225
            g.NavMoveDir = g.NavMoveDirForDebug;
13226
        g.NavMoveClipDir = g.NavMoveDir;
13227
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
13228
    }
13229
#endif
13230
13231
    // Submit
13232
80.5k
    g.NavMoveForwardToNextFrame = false;
13233
80.5k
    if (g.NavMoveDir != ImGuiDir_None)
13234
139
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
13235
13236
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
13237
80.5k
    if (g.NavMoveSubmitted && g.NavId == 0)
13238
15
    {
13239
15
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
13240
15
        g.NavInitRequest = g.NavInitRequestFromMove = true;
13241
15
        g.NavInitResult.ID = 0;
13242
15
        g.NavDisableHighlight = false;
13243
15
    }
13244
13245
    // When using gamepad, we project the reference nav bounding box into window visible area.
13246
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
13247
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
13248
80.5k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
13249
0
    {
13250
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
13251
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
13252
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
13253
13254
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
13255
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
13256
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
13257
13258
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
13259
0
        {
13260
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
13261
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
13262
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
13263
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
13264
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
13265
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
13266
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
13267
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
13268
0
            g.NavId = 0;
13269
0
        }
13270
0
    }
13271
13272
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
13273
80.5k
    ImRect scoring_rect;
13274
80.5k
    if (window != NULL)
13275
17.5k
    {
13276
17.5k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
13277
17.5k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
13278
17.5k
        scoring_rect.TranslateY(scoring_rect_offset_y);
13279
17.5k
        if (g.NavMoveSubmitted)
13280
139
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
13281
17.5k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
13282
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
13283
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
13284
17.5k
    }
13285
80.5k
    g.NavScoringRect = scoring_rect;
13286
80.5k
    g.NavScoringNoClipRect.Add(scoring_rect);
13287
80.5k
}
13288
13289
void ImGui::NavUpdateCreateTabbingRequest()
13290
80.4k
{
13291
80.4k
    ImGuiContext& g = *GImGui;
13292
80.4k
    ImGuiWindow* window = g.NavWindow;
13293
80.4k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
13294
80.4k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
13295
63.0k
        return;
13296
13297
17.3k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
13298
17.3k
    if (!tab_pressed)
13299
16.7k
        return;
13300
13301
    // Initiate tabbing request
13302
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
13303
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
13304
592
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13305
592
    if (nav_keyboard_active)
13306
592
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
13307
0
    else
13308
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
13309
592
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_IsTabbing | ImGuiNavMoveFlags_Activate;
13310
592
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
13311
592
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
13312
592
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
13313
592
    g.NavTabbingCounter = -1;
13314
592
}
13315
13316
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
13317
void ImGui::NavMoveRequestApplyResult()
13318
666
{
13319
666
    ImGuiContext& g = *GImGui;
13320
#if IMGUI_DEBUG_NAV_SCORING
13321
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
13322
        return;
13323
#endif
13324
13325
    // Select which result to use
13326
666
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
13327
13328
    // Tabbing forward wrap
13329
666
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && result == NULL)
13330
550
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
13331
0
            result = &g.NavTabbingResultFirst;
13332
13333
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
13334
666
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13335
666
    if (result == NULL)
13336
666
    {
13337
666
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13338
550
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
13339
666
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13340
110
            NavRestoreHighlightAfterMove();
13341
666
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
13342
666
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
13343
666
        return;
13344
666
    }
13345
13346
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
13347
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
13348
0
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
13349
0
            result = &g.NavMoveResultLocalVisible;
13350
13351
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
13352
0
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
13353
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
13354
0
            result = &g.NavMoveResultOther;
13355
0
    IM_ASSERT(g.NavWindow && result->Window);
13356
13357
    // Scroll to keep newly navigated item fully into view.
13358
0
    if (g.NavLayer == ImGuiNavLayer_Main)
13359
0
    {
13360
0
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
13361
0
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
13362
13363
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
13364
0
        {
13365
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
13366
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
13367
0
            SetScrollY(result->Window, scroll_target);
13368
0
        }
13369
0
    }
13370
13371
0
    if (g.NavWindow != result->Window)
13372
0
    {
13373
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
13374
0
        g.NavWindow = result->Window;
13375
0
        g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid;
13376
0
    }
13377
13378
    // Clear active id unless requested not to
13379
    // FIXME: ImGuiNavMoveFlags_NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction,
13380
    // so this is mostly provided as a gateway for further experiments (see #1418, #2890)
13381
0
    if (g.ActiveId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoClearActiveId) == 0)
13382
0
        ClearActiveID();
13383
13384
    // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
13385
    // PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior.
13386
0
    if ((g.NavId != result->ID || (g.NavMoveFlags & ImGuiNavMoveFlags_IsPageMove)) && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
13387
0
    {
13388
0
        g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId;
13389
0
        g.NavJustMovedToId = result->ID;
13390
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
13391
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
13392
0
        g.NavJustMovedToIsTabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) != 0;
13393
0
        g.NavJustMovedToHasSelectionData = (result->InFlags & ImGuiItemFlags_HasSelectionUserData) != 0;
13394
        //IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId);
13395
0
    }
13396
13397
    // Apply new NavID/Focus
13398
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
13399
0
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
13400
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
13401
0
    if (result->SelectionUserData != ImGuiSelectionUserData_Invalid)
13402
0
        g.NavLastValidSelectionUserData = result->SelectionUserData;
13403
13404
    // Restore last preferred position for current axis
13405
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
13406
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) == 0)
13407
0
    {
13408
0
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
13409
0
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
13410
0
    }
13411
13412
    // Tabbing: Activates Inputable, otherwise only Focus
13413
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
13414
0
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
13415
13416
    // Activate
13417
0
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
13418
0
    {
13419
0
        g.NavNextActivateId = result->ID;
13420
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
13421
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing)
13422
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing;
13423
0
    }
13424
13425
    // Enable nav highlight
13426
0
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
13427
0
        NavRestoreHighlightAfterMove();
13428
0
}
13429
13430
// Process NavCancel input (to close a popup, get back to parent, clear focus)
13431
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
13432
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
13433
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
13434
static void ImGui::NavUpdateCancelRequest()
13435
80.5k
{
13436
80.5k
    ImGuiContext& g = *GImGui;
13437
80.5k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13438
80.5k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13439
80.5k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, 0, ImGuiKeyOwner_NoOwner)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, 0, ImGuiKeyOwner_NoOwner)))
13440
79.7k
        return;
13441
13442
837
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
13443
837
    if (g.ActiveId != 0)
13444
0
    {
13445
0
        ClearActiveID();
13446
0
    }
13447
837
    else if (g.NavLayer != ImGuiNavLayer_Main)
13448
0
    {
13449
        // Leave the "menu" layer
13450
0
        NavRestoreLayer(ImGuiNavLayer_Main);
13451
0
        NavRestoreHighlightAfterMove();
13452
0
    }
13453
837
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow)
13454
47
    {
13455
        // Exit child window
13456
47
        ImGuiWindow* child_window = g.NavWindow->RootWindowForNav;
13457
47
        ImGuiWindow* parent_window = child_window->ParentWindow;
13458
47
        IM_ASSERT(child_window->ChildId != 0);
13459
47
        FocusWindow(parent_window);
13460
47
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_window->Rect()));
13461
47
        NavRestoreHighlightAfterMove();
13462
47
    }
13463
790
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
13464
0
    {
13465
        // Close open popup/menu
13466
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
13467
0
    }
13468
790
    else
13469
790
    {
13470
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
13471
790
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
13472
17
            g.NavWindow->NavLastIds[0] = 0;
13473
790
        g.NavId = 0;
13474
790
    }
13475
837
}
13476
13477
// Handle PageUp/PageDown/Home/End keys
13478
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
13479
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
13480
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
13481
static float ImGui::NavUpdatePageUpPageDown()
13482
17.4k
{
13483
17.4k
    ImGuiContext& g = *GImGui;
13484
17.4k
    ImGuiWindow* window = g.NavWindow;
13485
17.4k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
13486
0
        return 0.0f;
13487
13488
17.4k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_NoOwner);
13489
17.4k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_NoOwner);
13490
17.4k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13491
17.4k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner);
13492
17.4k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
13493
17.2k
        return 0.0f;
13494
13495
147
    if (g.NavLayer != ImGuiNavLayer_Main)
13496
1
        NavRestoreLayer(ImGuiNavLayer_Main);
13497
13498
147
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
13499
122
    {
13500
        // Fallback manual-scroll when window has no navigable item
13501
122
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13502
4
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
13503
118
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiInputFlags_Repeat, ImGuiKeyOwner_NoOwner))
13504
25
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
13505
93
        else if (home_pressed)
13506
16
            SetScrollY(window, 0.0f);
13507
77
        else if (end_pressed)
13508
11
            SetScrollY(window, window->ScrollMax.y);
13509
122
    }
13510
25
    else
13511
25
    {
13512
25
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
13513
25
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
13514
25
        float nav_scoring_rect_offset_y = 0.0f;
13515
25
        if (IsKeyPressed(ImGuiKey_PageUp, true))
13516
0
        {
13517
0
            nav_scoring_rect_offset_y = -page_offset_y;
13518
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
13519
0
            g.NavMoveClipDir = ImGuiDir_Up;
13520
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13521
0
        }
13522
25
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
13523
7
        {
13524
7
            nav_scoring_rect_offset_y = +page_offset_y;
13525
7
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
13526
7
            g.NavMoveClipDir = ImGuiDir_Down;
13527
7
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet | ImGuiNavMoveFlags_IsPageMove;
13528
7
        }
13529
18
        else if (home_pressed)
13530
7
        {
13531
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
13532
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
13533
            // Preserve current horizontal position if we have any.
13534
7
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
13535
7
            if (nav_rect_rel.IsInverted())
13536
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13537
7
            g.NavMoveDir = ImGuiDir_Down;
13538
7
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13539
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13540
7
        }
13541
11
        else if (end_pressed)
13542
1
        {
13543
1
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
13544
1
            if (nav_rect_rel.IsInverted())
13545
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
13546
1
            g.NavMoveDir = ImGuiDir_Up;
13547
1
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
13548
            // FIXME-NAV: MoveClipDir left to _None, intentional?
13549
1
        }
13550
25
        return nav_scoring_rect_offset_y;
13551
25
    }
13552
122
    return 0.0f;
13553
147
}
13554
13555
static void ImGui::NavEndFrame()
13556
80.5k
{
13557
80.5k
    ImGuiContext& g = *GImGui;
13558
13559
    // Show CTRL+TAB list window
13560
80.5k
    if (g.NavWindowingTarget != NULL)
13561
0
        NavUpdateWindowingOverlay();
13562
13563
    // Perform wrap-around in menus
13564
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
13565
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
13566
80.5k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
13567
0
        NavUpdateCreateWrappingRequest();
13568
80.5k
}
13569
13570
static void ImGui::NavUpdateCreateWrappingRequest()
13571
0
{
13572
0
    ImGuiContext& g = *GImGui;
13573
0
    ImGuiWindow* window = g.NavWindow;
13574
13575
0
    bool do_forward = false;
13576
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
13577
0
    ImGuiDir clip_dir = g.NavMoveDir;
13578
13579
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
13580
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
13581
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13582
0
    {
13583
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
13584
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13585
0
        {
13586
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
13587
0
            clip_dir = ImGuiDir_Up;
13588
0
        }
13589
0
        do_forward = true;
13590
0
    }
13591
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
13592
0
    {
13593
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
13594
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
13595
0
        {
13596
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
13597
0
            clip_dir = ImGuiDir_Down;
13598
0
        }
13599
0
        do_forward = true;
13600
0
    }
13601
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13602
0
    {
13603
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
13604
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13605
0
        {
13606
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
13607
0
            clip_dir = ImGuiDir_Left;
13608
0
        }
13609
0
        do_forward = true;
13610
0
    }
13611
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
13612
0
    {
13613
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
13614
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
13615
0
        {
13616
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
13617
0
            clip_dir = ImGuiDir_Right;
13618
0
        }
13619
0
        do_forward = true;
13620
0
    }
13621
0
    if (!do_forward)
13622
0
        return;
13623
0
    window->NavRectRel[g.NavLayer] = bb_rel;
13624
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
13625
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
13626
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
13627
0
}
13628
13629
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
13630
0
{
13631
0
    ImGuiContext& g = *GImGui;
13632
0
    IM_UNUSED(g);
13633
0
    int order = window->FocusOrder;
13634
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
13635
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
13636
0
    return order;
13637
0
}
13638
13639
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
13640
0
{
13641
0
    ImGuiContext& g = *GImGui;
13642
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
13643
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
13644
0
            return g.WindowsFocusOrder[i];
13645
0
    return NULL;
13646
0
}
13647
13648
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
13649
0
{
13650
0
    ImGuiContext& g = *GImGui;
13651
0
    IM_ASSERT(g.NavWindowingTarget);
13652
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
13653
0
        return;
13654
13655
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
13656
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
13657
0
    if (!window_target)
13658
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
13659
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
13660
0
    {
13661
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
13662
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13663
0
    }
13664
0
    g.NavWindowingToggleLayer = false;
13665
0
}
13666
13667
// Windowing management mode
13668
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
13669
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
13670
static void ImGui::NavUpdateWindowing()
13671
80.5k
{
13672
80.5k
    ImGuiContext& g = *GImGui;
13673
80.5k
    ImGuiIO& io = g.IO;
13674
13675
80.5k
    ImGuiWindow* apply_focus_window = NULL;
13676
80.5k
    bool apply_toggle_layer = false;
13677
13678
80.5k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
13679
80.5k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
13680
80.5k
    if (!allow_windowing)
13681
0
        g.NavWindowingTarget = NULL;
13682
13683
    // Fade out
13684
80.5k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
13685
0
    {
13686
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
13687
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
13688
0
            g.NavWindowingTargetAnim = NULL;
13689
0
    }
13690
13691
    // Start CTRL+Tab or Square+L/R window selection
13692
    // (g.ConfigNavWindowingKeyNext/g.ConfigNavWindowingKeyPrev defaults are ImGuiMod_Ctrl|ImGuiKey_Tab and ImGuiMod_Ctrl|ImGuiMod_Shift|ImGuiKey_Tab)
13693
80.5k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
13694
80.5k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
13695
80.5k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
13696
80.5k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13697
80.5k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways, owner_id);
13698
80.5k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, ImGuiInputFlags_None);
13699
80.5k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
13700
80.5k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
13701
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
13702
0
        {
13703
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
13704
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
13705
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
13706
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
13707
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
13708
13709
            // Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects.
13710
0
            if (keyboard_next_window || keyboard_prev_window)
13711
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
13712
0
        }
13713
13714
    // Gamepad update
13715
80.5k
    g.NavWindowingTimer += io.DeltaTime;
13716
80.5k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
13717
0
    {
13718
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
13719
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
13720
13721
        // Select window to focus
13722
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
13723
0
        if (focus_change_dir != 0)
13724
0
        {
13725
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
13726
0
            g.NavWindowingHighlightAlpha = 1.0f;
13727
0
        }
13728
13729
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
13730
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
13731
0
        {
13732
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
13733
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
13734
0
                apply_toggle_layer = true;
13735
0
            else if (!g.NavWindowingToggleLayer)
13736
0
                apply_focus_window = g.NavWindowingTarget;
13737
0
            g.NavWindowingTarget = NULL;
13738
0
        }
13739
0
    }
13740
13741
    // Keyboard: Focus
13742
80.5k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
13743
0
    {
13744
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
13745
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
13746
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
13747
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
13748
0
        if (keyboard_next_window || keyboard_prev_window)
13749
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
13750
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
13751
0
            apply_focus_window = g.NavWindowingTarget;
13752
0
    }
13753
13754
    // Keyboard: Press and Release ALT to toggle menu layer
13755
80.5k
    const ImGuiKey windowing_toggle_keys[] = { ImGuiKey_LeftAlt, ImGuiKey_RightAlt };
13756
80.5k
    for (ImGuiKey windowing_toggle_key : windowing_toggle_keys)
13757
161k
        if (nav_keyboard_active && IsKeyPressed(windowing_toggle_key, 0, ImGuiKeyOwner_NoOwner))
13758
1.68k
        {
13759
1.68k
            g.NavWindowingToggleLayer = true;
13760
1.68k
            g.NavWindowingToggleKey = windowing_toggle_key;
13761
1.68k
            g.NavInputSource = ImGuiInputSource_Keyboard;
13762
1.68k
            break;
13763
1.68k
        }
13764
80.5k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
13765
4.06k
    {
13766
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
13767
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
13768
        // - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl).
13769
        // We cancel toggling nav layer if an owner has claimed the key.
13770
4.06k
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)
13771
235
            g.NavWindowingToggleLayer = false;
13772
4.06k
        if (TestKeyOwner(g.NavWindowingToggleKey, ImGuiKeyOwner_NoOwner) == false || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_NoOwner) == false)
13773
0
            g.NavWindowingToggleLayer = false;
13774
13775
        // Apply layer toggle on Alt release
13776
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
13777
4.06k
        if (IsKeyReleased(g.NavWindowingToggleKey) && g.NavWindowingToggleLayer)
13778
1.22k
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
13779
1.22k
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
13780
1.22k
                    apply_toggle_layer = true;
13781
4.06k
        if (!IsKeyDown(g.NavWindowingToggleKey))
13782
1.50k
            g.NavWindowingToggleLayer = false;
13783
4.06k
    }
13784
13785
    // Move window
13786
80.5k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
13787
0
    {
13788
0
        ImVec2 nav_move_dir;
13789
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
13790
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
13791
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
13792
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
13793
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
13794
0
        {
13795
0
            const float NAV_MOVE_SPEED = 800.0f;
13796
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
13797
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
13798
0
            g.NavDisableMouseHover = true;
13799
0
            ImVec2 accum_floored = ImTrunc(g.NavWindowingAccumDeltaPos);
13800
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
13801
0
            {
13802
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
13803
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
13804
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
13805
0
            }
13806
0
        }
13807
0
    }
13808
13809
    // Apply final focus
13810
80.5k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
13811
0
    {
13812
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
13813
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
13814
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
13815
0
        ClearActiveID();
13816
0
        NavRestoreHighlightAfterMove();
13817
0
        ClosePopupsOverWindow(apply_focus_window, false);
13818
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
13819
0
        apply_focus_window = g.NavWindow;
13820
0
        if (apply_focus_window->NavLastIds[0] == 0)
13821
0
            NavInitWindow(apply_focus_window, false);
13822
13823
        // If the window has ONLY a menu layer (no main layer), select it directly
13824
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
13825
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
13826
        // the target window as already been previewed once.
13827
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
13828
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
13829
        // won't be valid.
13830
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
13831
0
            g.NavLayer = ImGuiNavLayer_Menu;
13832
13833
        // Request OS level focus
13834
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
13835
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
13836
0
    }
13837
80.5k
    if (apply_focus_window)
13838
0
        g.NavWindowingTarget = NULL;
13839
13840
    // Apply menu/layer toggle
13841
80.5k
    if (apply_toggle_layer && g.NavWindow)
13842
117
    {
13843
117
        ClearActiveID();
13844
13845
        // Move to parent menu if necessary
13846
117
        ImGuiWindow* new_nav_window = g.NavWindow;
13847
222
        while (new_nav_window->ParentWindow
13848
222
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
13849
222
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
13850
222
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
13851
105
            new_nav_window = new_nav_window->ParentWindow;
13852
117
        if (new_nav_window != g.NavWindow)
13853
105
        {
13854
105
            ImGuiWindow* old_nav_window = g.NavWindow;
13855
105
            FocusWindow(new_nav_window);
13856
105
            new_nav_window->NavLastChildNavWindow = old_nav_window;
13857
105
        }
13858
13859
        // Toggle layer
13860
117
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
13861
117
        if (new_nav_layer != g.NavLayer)
13862
117
        {
13863
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
13864
117
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
13865
117
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
13866
105
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
13867
117
            NavRestoreLayer(new_nav_layer);
13868
117
            NavRestoreHighlightAfterMove();
13869
117
        }
13870
117
    }
13871
80.5k
}
13872
13873
// Window has already passed the IsWindowNavFocusable()
13874
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
13875
0
{
13876
0
    if (window->Flags & ImGuiWindowFlags_Popup)
13877
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
13878
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
13879
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
13880
0
    if (window->DockNodeAsHost)
13881
0
        return "(Dock node)"; // Not normally shown to user.
13882
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
13883
0
}
13884
13885
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
13886
void ImGui::NavUpdateWindowingOverlay()
13887
0
{
13888
0
    ImGuiContext& g = *GImGui;
13889
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
13890
13891
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
13892
0
        return;
13893
13894
0
    if (g.NavWindowingListWindow == NULL)
13895
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
13896
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
13897
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
13898
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
13899
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
13900
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
13901
0
    if (g.ContextName[0] != 0)
13902
0
        SeparatorText(g.ContextName);
13903
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
13904
0
    {
13905
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
13906
0
        IM_ASSERT(window != NULL); // Fix static analyzers
13907
0
        if (!IsWindowNavFocusable(window))
13908
0
            continue;
13909
0
        const char* label = window->Name;
13910
0
        if (label == FindRenderedTextEnd(label))
13911
0
            label = GetFallbackWindowNameForWindowingList(window);
13912
0
        Selectable(label, g.NavWindowingTarget == window);
13913
0
    }
13914
0
    End();
13915
0
    PopStyleVar();
13916
0
}
13917
13918
13919
//-----------------------------------------------------------------------------
13920
// [SECTION] DRAG AND DROP
13921
//-----------------------------------------------------------------------------
13922
13923
bool ImGui::IsDragDropActive()
13924
0
{
13925
0
    ImGuiContext& g = *GImGui;
13926
0
    return g.DragDropActive;
13927
0
}
13928
13929
void ImGui::ClearDragDrop()
13930
18
{
13931
18
    ImGuiContext& g = *GImGui;
13932
18
    if (g.DragDropActive)
13933
9
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] ClearDragDrop()\n");
13934
18
    g.DragDropActive = false;
13935
18
    g.DragDropPayload.Clear();
13936
18
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
13937
18
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
13938
18
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
13939
18
    g.DragDropAcceptFrameCount = -1;
13940
13941
18
    g.DragDropPayloadBufHeap.clear();
13942
18
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13943
18
}
13944
13945
bool ImGui::BeginTooltipHidden()
13946
0
{
13947
0
    ImGuiContext& g = *GImGui;
13948
0
    bool ret = Begin("##Tooltip_Hidden", NULL, ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize);
13949
0
    SetWindowHiddenAndSkipItemsForCurrentFrame(g.CurrentWindow);
13950
0
    return ret;
13951
0
}
13952
13953
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
13954
// If the item has an identifier:
13955
// - This assume/require the item to be activated (typically via ButtonBehavior).
13956
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13957
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13958
// If the item has no identifier:
13959
// - Currently always assume left mouse button.
13960
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13961
4.73k
{
13962
4.73k
    ImGuiContext& g = *GImGui;
13963
4.73k
    ImGuiWindow* window = g.CurrentWindow;
13964
13965
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13966
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13967
4.73k
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13968
13969
4.73k
    bool source_drag_active = false;
13970
4.73k
    ImGuiID source_id = 0;
13971
4.73k
    ImGuiID source_parent_id = 0;
13972
4.73k
    if ((flags & ImGuiDragDropFlags_SourceExtern) == 0)
13973
4.73k
    {
13974
4.73k
        source_id = g.LastItemData.ID;
13975
4.73k
        if (source_id != 0)
13976
4.73k
        {
13977
            // Common path: items with ID
13978
4.73k
            if (g.ActiveId != source_id)
13979
0
                return false;
13980
4.73k
            if (g.ActiveIdMouseButton != -1)
13981
0
                mouse_button = g.ActiveIdMouseButton;
13982
4.73k
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13983
0
                return false;
13984
4.73k
            g.ActiveIdAllowOverlap = false;
13985
4.73k
        }
13986
0
        else
13987
0
        {
13988
            // Uncommon path: items without ID
13989
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13990
0
                return false;
13991
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13992
0
                return false;
13993
13994
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13995
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13996
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13997
0
            {
13998
0
                IM_ASSERT(0);
13999
0
                return false;
14000
0
            }
14001
14002
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
14003
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
14004
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
14005
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
14006
            // Rely on keeping other window->LastItemXXX fields intact.
14007
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
14008
0
            KeepAliveID(source_id);
14009
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
14010
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
14011
0
            {
14012
0
                SetActiveID(source_id, window);
14013
0
                FocusWindow(window);
14014
0
            }
14015
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
14016
0
                g.ActiveIdAllowOverlap = is_hovered;
14017
0
        }
14018
4.73k
        if (g.ActiveId != source_id)
14019
0
            return false;
14020
4.73k
        source_parent_id = window->IDStack.back();
14021
4.73k
        source_drag_active = IsMouseDragging(mouse_button);
14022
14023
        // Disable navigation and key inputs while dragging + cancel existing request if any
14024
4.73k
        SetActiveIdUsingAllKeyboardKeys();
14025
4.73k
    }
14026
0
    else
14027
0
    {
14028
        // When ImGuiDragDropFlags_SourceExtern is set:
14029
0
        window = NULL;
14030
0
        source_id = ImHashStr("#SourceExtern");
14031
0
        source_drag_active = true;
14032
0
        mouse_button = g.IO.MouseDown[0] ? 0 : -1;
14033
0
        KeepAliveID(source_id);
14034
0
        SetActiveID(source_id, NULL);
14035
0
    }
14036
14037
4.73k
    IM_ASSERT(g.DragDropWithinTarget == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14038
4.73k
    if (!source_drag_active)
14039
1.25k
        return false;
14040
14041
    // Activate drag and drop
14042
3.48k
    if (!g.DragDropActive)
14043
9
    {
14044
9
        IM_ASSERT(source_id != 0);
14045
9
        ClearDragDrop();
14046
9
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] BeginDragDropSource() DragDropActive = true, source_id = 0x%08X%s\n",
14047
9
            source_id, (flags & ImGuiDragDropFlags_SourceExtern) ? " (EXTERN)" : "");
14048
9
        ImGuiPayload& payload = g.DragDropPayload;
14049
9
        payload.SourceId = source_id;
14050
9
        payload.SourceParentId = source_parent_id;
14051
9
        g.DragDropActive = true;
14052
9
        g.DragDropSourceFlags = flags;
14053
9
        g.DragDropMouseButton = mouse_button;
14054
9
        if (payload.SourceId == g.ActiveId)
14055
9
            g.ActiveIdNoClearOnFocusLoss = true;
14056
9
    }
14057
3.48k
    g.DragDropSourceFrameCount = g.FrameCount;
14058
3.48k
    g.DragDropWithinSource = true;
14059
14060
3.48k
    if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14061
0
    {
14062
        // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
14063
        // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
14064
0
        bool ret;
14065
0
        if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
14066
0
            ret = BeginTooltipHidden();
14067
0
        else
14068
0
            ret = BeginTooltip();
14069
0
        IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
14070
0
        IM_UNUSED(ret);
14071
0
    }
14072
14073
3.48k
    if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
14074
3.48k
        g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
14075
14076
3.48k
    return true;
14077
4.73k
}
14078
14079
void ImGui::EndDragDropSource()
14080
3.48k
{
14081
3.48k
    ImGuiContext& g = *GImGui;
14082
3.48k
    IM_ASSERT(g.DragDropActive);
14083
3.48k
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
14084
14085
3.48k
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
14086
0
        EndTooltip();
14087
14088
    // Discard the drag if have not called SetDragDropPayload()
14089
3.48k
    if (g.DragDropPayload.DataFrameCount == -1)
14090
0
        ClearDragDrop();
14091
3.48k
    g.DragDropWithinSource = false;
14092
3.48k
}
14093
14094
// Use 'cond' to choose to submit payload on drag start or every frame
14095
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
14096
3.48k
{
14097
3.48k
    ImGuiContext& g = *GImGui;
14098
3.48k
    ImGuiPayload& payload = g.DragDropPayload;
14099
3.48k
    if (cond == 0)
14100
3.48k
        cond = ImGuiCond_Always;
14101
14102
3.48k
    IM_ASSERT(type != NULL);
14103
3.48k
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
14104
3.48k
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
14105
3.48k
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
14106
3.48k
    IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
14107
14108
3.48k
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
14109
3.48k
    {
14110
        // Copy payload
14111
3.48k
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
14112
3.48k
        g.DragDropPayloadBufHeap.resize(0);
14113
3.48k
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
14114
0
        {
14115
            // Store in heap
14116
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
14117
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
14118
0
            memcpy(payload.Data, data, data_size);
14119
0
        }
14120
3.48k
        else if (data_size > 0)
14121
3.48k
        {
14122
            // Store locally
14123
3.48k
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
14124
3.48k
            payload.Data = g.DragDropPayloadBufLocal;
14125
3.48k
            memcpy(payload.Data, data, data_size);
14126
3.48k
        }
14127
0
        else
14128
0
        {
14129
0
            payload.Data = NULL;
14130
0
        }
14131
3.48k
        payload.DataSize = (int)data_size;
14132
3.48k
    }
14133
3.48k
    payload.DataFrameCount = g.FrameCount;
14134
14135
    // Return whether the payload has been accepted
14136
3.48k
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
14137
3.48k
}
14138
14139
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
14140
3.51k
{
14141
3.51k
    ImGuiContext& g = *GImGui;
14142
3.51k
    if (!g.DragDropActive)
14143
0
        return false;
14144
14145
3.51k
    ImGuiWindow* window = g.CurrentWindow;
14146
3.51k
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14147
3.51k
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
14148
3.50k
        return false;
14149
5
    IM_ASSERT(id != 0);
14150
5
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
14151
0
        return false;
14152
5
    if (window->SkipItems)
14153
0
        return false;
14154
14155
5
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14156
5
    g.DragDropTargetRect = bb;
14157
5
    g.DragDropTargetClipRect = window->ClipRect; // May want to be overridden by user depending on use case?
14158
5
    g.DragDropTargetId = id;
14159
5
    g.DragDropWithinTarget = true;
14160
5
    return true;
14161
5
}
14162
14163
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
14164
// 1) we use LastItemData's ImGuiItemStatusFlags_HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
14165
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
14166
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
14167
bool ImGui::BeginDragDropTarget()
14168
0
{
14169
0
    ImGuiContext& g = *GImGui;
14170
0
    if (!g.DragDropActive)
14171
0
        return false;
14172
14173
0
    ImGuiWindow* window = g.CurrentWindow;
14174
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
14175
0
        return false;
14176
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
14177
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
14178
0
        return false;
14179
14180
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
14181
0
    ImGuiID id = g.LastItemData.ID;
14182
0
    if (id == 0)
14183
0
    {
14184
0
        id = window->GetIDFromRectangle(display_rect);
14185
0
        KeepAliveID(id);
14186
0
    }
14187
0
    if (g.DragDropPayload.SourceId == id)
14188
0
        return false;
14189
14190
0
    IM_ASSERT(g.DragDropWithinTarget == false && g.DragDropWithinSource == false); // Can't nest BeginDragDropSource() and BeginDragDropTarget()
14191
0
    g.DragDropTargetRect = display_rect;
14192
0
    g.DragDropTargetClipRect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasClipRect) ? g.LastItemData.ClipRect : window->ClipRect;
14193
0
    g.DragDropTargetId = id;
14194
0
    g.DragDropWithinTarget = true;
14195
0
    return true;
14196
0
}
14197
14198
bool ImGui::IsDragDropPayloadBeingAccepted()
14199
163
{
14200
163
    ImGuiContext& g = *GImGui;
14201
163
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
14202
163
}
14203
14204
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
14205
5
{
14206
5
    ImGuiContext& g = *GImGui;
14207
5
    ImGuiPayload& payload = g.DragDropPayload;
14208
5
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
14209
5
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
14210
5
    if (type != NULL && !payload.IsDataType(type))
14211
0
        return NULL;
14212
14213
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
14214
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
14215
5
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
14216
5
    ImRect r = g.DragDropTargetRect;
14217
5
    float r_surface = r.GetWidth() * r.GetHeight();
14218
5
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
14219
0
        return NULL;
14220
14221
5
    g.DragDropAcceptFlags = flags;
14222
5
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
14223
5
    g.DragDropAcceptIdCurrRectSurface = r_surface;
14224
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
14225
14226
    // Render default drop visuals
14227
5
    payload.Preview = was_accepted_previously;
14228
5
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
14229
5
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
14230
0
        RenderDragDropTargetRect(r, g.DragDropTargetClipRect);
14231
14232
5
    g.DragDropAcceptFrameCount = g.FrameCount;
14233
5
    if ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) && g.DragDropMouseButton == -1)
14234
0
        payload.Delivery = was_accepted_previously && (g.DragDropSourceFrameCount < g.FrameCount);
14235
5
    else
14236
5
        payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
14237
5
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
14238
0
        return NULL;
14239
14240
5
    if (payload.Delivery)
14241
0
        IMGUI_DEBUG_LOG_ACTIVEID("[dragdrop] AcceptDragDropPayload(): 0x%08X: payload delivery\n", g.DragDropTargetId);
14242
5
    return &payload;
14243
5
}
14244
14245
// FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
14246
void ImGui::RenderDragDropTargetRect(const ImRect& bb, const ImRect& item_clip_rect)
14247
0
{
14248
0
    ImGuiContext& g = *GImGui;
14249
0
    ImGuiWindow* window = g.CurrentWindow;
14250
0
    ImRect bb_display = bb;
14251
0
    bb_display.ClipWith(item_clip_rect); // Clip THEN expand so we have a way to visualize that target is not entirely visible.
14252
0
    bb_display.Expand(3.5f);
14253
0
    bool push_clip_rect = !window->ClipRect.Contains(bb_display);
14254
0
    if (push_clip_rect)
14255
0
        window->DrawList->PushClipRectFullScreen();
14256
0
    window->DrawList->AddRect(bb_display.Min, bb_display.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
14257
0
    if (push_clip_rect)
14258
0
        window->DrawList->PopClipRect();
14259
0
}
14260
14261
const ImGuiPayload* ImGui::GetDragDropPayload()
14262
0
{
14263
0
    ImGuiContext& g = *GImGui;
14264
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
14265
0
}
14266
14267
void ImGui::EndDragDropTarget()
14268
5
{
14269
5
    ImGuiContext& g = *GImGui;
14270
5
    IM_ASSERT(g.DragDropActive);
14271
5
    IM_ASSERT(g.DragDropWithinTarget);
14272
5
    g.DragDropWithinTarget = false;
14273
14274
    // Clear drag and drop state payload right after delivery
14275
5
    if (g.DragDropPayload.Delivery)
14276
0
        ClearDragDrop();
14277
5
}
14278
14279
//-----------------------------------------------------------------------------
14280
// [SECTION] LOGGING/CAPTURING
14281
//-----------------------------------------------------------------------------
14282
// All text output from the interface can be captured into tty/file/clipboard.
14283
// By default, tree nodes are automatically opened during logging.
14284
//-----------------------------------------------------------------------------
14285
14286
// Pass text data straight to log (without being displayed)
14287
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
14288
0
{
14289
0
    if (g.LogFile)
14290
0
    {
14291
0
        g.LogBuffer.Buf.resize(0);
14292
0
        g.LogBuffer.appendfv(fmt, args);
14293
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
14294
0
    }
14295
0
    else
14296
0
    {
14297
0
        g.LogBuffer.appendfv(fmt, args);
14298
0
    }
14299
0
}
14300
14301
void ImGui::LogText(const char* fmt, ...)
14302
0
{
14303
0
    ImGuiContext& g = *GImGui;
14304
0
    if (!g.LogEnabled)
14305
0
        return;
14306
14307
0
    va_list args;
14308
0
    va_start(args, fmt);
14309
0
    LogTextV(g, fmt, args);
14310
0
    va_end(args);
14311
0
}
14312
14313
void ImGui::LogTextV(const char* fmt, va_list args)
14314
0
{
14315
0
    ImGuiContext& g = *GImGui;
14316
0
    if (!g.LogEnabled)
14317
0
        return;
14318
14319
0
    LogTextV(g, fmt, args);
14320
0
}
14321
14322
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
14323
// We split text into individual lines to add current tree level padding
14324
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
14325
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
14326
0
{
14327
0
    ImGuiContext& g = *GImGui;
14328
0
    ImGuiWindow* window = g.CurrentWindow;
14329
14330
0
    const char* prefix = g.LogNextPrefix;
14331
0
    const char* suffix = g.LogNextSuffix;
14332
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14333
14334
0
    if (!text_end)
14335
0
        text_end = FindRenderedTextEnd(text, text_end);
14336
14337
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
14338
0
    if (ref_pos)
14339
0
        g.LogLinePosY = ref_pos->y;
14340
0
    if (log_new_line)
14341
0
    {
14342
0
        LogText(IM_NEWLINE);
14343
0
        g.LogLineFirstItem = true;
14344
0
    }
14345
14346
0
    if (prefix)
14347
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
14348
14349
    // Re-adjust padding if we have popped out of our starting depth
14350
0
    if (g.LogDepthRef > window->DC.TreeDepth)
14351
0
        g.LogDepthRef = window->DC.TreeDepth;
14352
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
14353
14354
0
    const char* text_remaining = text;
14355
0
    for (;;)
14356
0
    {
14357
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
14358
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
14359
0
        const char* line_start = text_remaining;
14360
0
        const char* line_end = ImStreolRange(line_start, text_end);
14361
0
        const bool is_last_line = (line_end == text_end);
14362
0
        if (line_start != line_end || !is_last_line)
14363
0
        {
14364
0
            const int line_length = (int)(line_end - line_start);
14365
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
14366
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
14367
0
            g.LogLineFirstItem = false;
14368
0
            if (*line_end == '\n')
14369
0
            {
14370
0
                LogText(IM_NEWLINE);
14371
0
                g.LogLineFirstItem = true;
14372
0
            }
14373
0
        }
14374
0
        if (is_last_line)
14375
0
            break;
14376
0
        text_remaining = line_end + 1;
14377
0
    }
14378
14379
0
    if (suffix)
14380
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
14381
0
}
14382
14383
// Start logging/capturing text output
14384
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
14385
0
{
14386
0
    ImGuiContext& g = *GImGui;
14387
0
    ImGuiWindow* window = g.CurrentWindow;
14388
0
    IM_ASSERT(g.LogEnabled == false);
14389
0
    IM_ASSERT(g.LogFile == NULL);
14390
0
    IM_ASSERT(g.LogBuffer.empty());
14391
0
    g.LogEnabled = g.ItemUnclipByLog = true;
14392
0
    g.LogType = type;
14393
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
14394
0
    g.LogDepthRef = window->DC.TreeDepth;
14395
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
14396
0
    g.LogLinePosY = FLT_MAX;
14397
0
    g.LogLineFirstItem = true;
14398
0
}
14399
14400
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
14401
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
14402
0
{
14403
0
    ImGuiContext& g = *GImGui;
14404
0
    g.LogNextPrefix = prefix;
14405
0
    g.LogNextSuffix = suffix;
14406
0
}
14407
14408
void ImGui::LogToTTY(int auto_open_depth)
14409
0
{
14410
0
    ImGuiContext& g = *GImGui;
14411
0
    if (g.LogEnabled)
14412
0
        return;
14413
0
    IM_UNUSED(auto_open_depth);
14414
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14415
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
14416
0
    g.LogFile = stdout;
14417
0
#endif
14418
0
}
14419
14420
// Start logging/capturing text output to given file
14421
void ImGui::LogToFile(int auto_open_depth, const char* filename)
14422
0
{
14423
0
    ImGuiContext& g = *GImGui;
14424
0
    if (g.LogEnabled)
14425
0
        return;
14426
14427
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
14428
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
14429
    // By opening the file in binary mode "ab" we have consistent output everywhere.
14430
0
    if (!filename)
14431
0
        filename = g.IO.LogFilename;
14432
0
    if (!filename || !filename[0])
14433
0
        return;
14434
0
    ImFileHandle f = ImFileOpen(filename, "ab");
14435
0
    if (!f)
14436
0
    {
14437
0
        IM_ASSERT(0);
14438
0
        return;
14439
0
    }
14440
14441
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
14442
0
    g.LogFile = f;
14443
0
}
14444
14445
// Start logging/capturing text output to clipboard
14446
void ImGui::LogToClipboard(int auto_open_depth)
14447
0
{
14448
0
    ImGuiContext& g = *GImGui;
14449
0
    if (g.LogEnabled)
14450
0
        return;
14451
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
14452
0
}
14453
14454
void ImGui::LogToBuffer(int auto_open_depth)
14455
0
{
14456
0
    ImGuiContext& g = *GImGui;
14457
0
    if (g.LogEnabled)
14458
0
        return;
14459
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
14460
0
}
14461
14462
void ImGui::LogFinish()
14463
161k
{
14464
161k
    ImGuiContext& g = *GImGui;
14465
161k
    if (!g.LogEnabled)
14466
161k
        return;
14467
14468
0
    LogText(IM_NEWLINE);
14469
0
    switch (g.LogType)
14470
0
    {
14471
0
    case ImGuiLogType_TTY:
14472
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14473
0
        fflush(g.LogFile);
14474
0
#endif
14475
0
        break;
14476
0
    case ImGuiLogType_File:
14477
0
        ImFileClose(g.LogFile);
14478
0
        break;
14479
0
    case ImGuiLogType_Buffer:
14480
0
        break;
14481
0
    case ImGuiLogType_Clipboard:
14482
0
        if (!g.LogBuffer.empty())
14483
0
            SetClipboardText(g.LogBuffer.begin());
14484
0
        break;
14485
0
    case ImGuiLogType_None:
14486
0
        IM_ASSERT(0);
14487
0
        break;
14488
0
    }
14489
14490
0
    g.LogEnabled = g.ItemUnclipByLog = false;
14491
0
    g.LogType = ImGuiLogType_None;
14492
0
    g.LogFile = NULL;
14493
0
    g.LogBuffer.clear();
14494
0
}
14495
14496
// Helper to display logging buttons
14497
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
14498
void ImGui::LogButtons()
14499
0
{
14500
0
    ImGuiContext& g = *GImGui;
14501
14502
0
    PushID("LogButtons");
14503
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
14504
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
14505
#else
14506
    const bool log_to_tty = false;
14507
#endif
14508
0
    const bool log_to_file = Button("Log To File"); SameLine();
14509
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
14510
0
    PushItemFlag(ImGuiItemFlags_NoTabStop, true);
14511
0
    SetNextItemWidth(80.0f);
14512
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
14513
0
    PopItemFlag();
14514
0
    PopID();
14515
14516
    // Start logging at the end of the function so that the buttons don't appear in the log
14517
0
    if (log_to_tty)
14518
0
        LogToTTY();
14519
0
    if (log_to_file)
14520
0
        LogToFile();
14521
0
    if (log_to_clipboard)
14522
0
        LogToClipboard();
14523
0
}
14524
14525
14526
//-----------------------------------------------------------------------------
14527
// [SECTION] SETTINGS
14528
//-----------------------------------------------------------------------------
14529
// - UpdateSettings() [Internal]
14530
// - MarkIniSettingsDirty() [Internal]
14531
// - FindSettingsHandler() [Internal]
14532
// - ClearIniSettings() [Internal]
14533
// - LoadIniSettingsFromDisk()
14534
// - LoadIniSettingsFromMemory()
14535
// - SaveIniSettingsToDisk()
14536
// - SaveIniSettingsToMemory()
14537
//-----------------------------------------------------------------------------
14538
// - CreateNewWindowSettings() [Internal]
14539
// - FindWindowSettingsByID() [Internal]
14540
// - FindWindowSettingsByWindow() [Internal]
14541
// - ClearWindowSettings() [Internal]
14542
// - WindowSettingsHandler_***() [Internal]
14543
//-----------------------------------------------------------------------------
14544
14545
// Called by NewFrame()
14546
void ImGui::UpdateSettings()
14547
80.5k
{
14548
    // Load settings on first frame (if not explicitly loaded manually before)
14549
80.5k
    ImGuiContext& g = *GImGui;
14550
80.5k
    if (!g.SettingsLoaded)
14551
1
    {
14552
1
        IM_ASSERT(g.SettingsWindows.empty());
14553
1
        if (g.IO.IniFilename)
14554
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
14555
1
        g.SettingsLoaded = true;
14556
1
    }
14557
14558
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
14559
80.5k
    if (g.SettingsDirtyTimer > 0.0f)
14560
6.32k
    {
14561
6.32k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
14562
6.32k
        if (g.SettingsDirtyTimer <= 0.0f)
14563
21
        {
14564
21
            if (g.IO.IniFilename != NULL)
14565
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
14566
21
            else
14567
21
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
14568
21
            g.SettingsDirtyTimer = 0.0f;
14569
21
        }
14570
6.32k
    }
14571
80.5k
}
14572
14573
void ImGui::MarkIniSettingsDirty()
14574
0
{
14575
0
    ImGuiContext& g = *GImGui;
14576
0
    if (g.SettingsDirtyTimer <= 0.0f)
14577
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
14578
0
}
14579
14580
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
14581
25.2k
{
14582
25.2k
    ImGuiContext& g = *GImGui;
14583
25.2k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
14584
149
        if (g.SettingsDirtyTimer <= 0.0f)
14585
22
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
14586
25.2k
}
14587
14588
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
14589
2
{
14590
2
    ImGuiContext& g = *GImGui;
14591
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
14592
2
    g.SettingsHandlers.push_back(*handler);
14593
2
}
14594
14595
void ImGui::RemoveSettingsHandler(const char* type_name)
14596
0
{
14597
0
    ImGuiContext& g = *GImGui;
14598
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
14599
0
        g.SettingsHandlers.erase(handler);
14600
0
}
14601
14602
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
14603
2
{
14604
2
    ImGuiContext& g = *GImGui;
14605
2
    const ImGuiID type_hash = ImHashStr(type_name);
14606
2
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14607
1
        if (handler.TypeHash == type_hash)
14608
0
            return &handler;
14609
2
    return NULL;
14610
2
}
14611
14612
// Clear all settings (windows, tables, docking etc.)
14613
void ImGui::ClearIniSettings()
14614
0
{
14615
0
    ImGuiContext& g = *GImGui;
14616
0
    g.SettingsIniData.clear();
14617
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14618
0
        if (handler.ClearAllFn != NULL)
14619
0
            handler.ClearAllFn(&g, &handler);
14620
0
}
14621
14622
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
14623
0
{
14624
0
    size_t file_data_size = 0;
14625
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
14626
0
    if (!file_data)
14627
0
        return;
14628
0
    if (file_data_size > 0)
14629
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
14630
0
    IM_FREE(file_data);
14631
0
}
14632
14633
// Zero-tolerance, no error reporting, cheap .ini parsing
14634
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
14635
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
14636
0
{
14637
0
    ImGuiContext& g = *GImGui;
14638
0
    IM_ASSERT(g.Initialized);
14639
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
14640
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
14641
14642
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
14643
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
14644
0
    if (ini_size == 0)
14645
0
        ini_size = strlen(ini_data);
14646
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
14647
0
    char* const buf = g.SettingsIniData.Buf.Data;
14648
0
    char* const buf_end = buf + ini_size;
14649
0
    memcpy(buf, ini_data, ini_size);
14650
0
    buf_end[0] = 0;
14651
14652
    // Call pre-read handlers
14653
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
14654
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14655
0
        if (handler.ReadInitFn != NULL)
14656
0
            handler.ReadInitFn(&g, &handler);
14657
14658
0
    void* entry_data = NULL;
14659
0
    ImGuiSettingsHandler* entry_handler = NULL;
14660
14661
0
    char* line_end = NULL;
14662
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
14663
0
    {
14664
        // Skip new lines markers, then find end of the line
14665
0
        while (*line == '\n' || *line == '\r')
14666
0
            line++;
14667
0
        line_end = line;
14668
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
14669
0
            line_end++;
14670
0
        line_end[0] = 0;
14671
0
        if (line[0] == ';')
14672
0
            continue;
14673
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
14674
0
        {
14675
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
14676
0
            line_end[-1] = 0;
14677
0
            const char* name_end = line_end - 1;
14678
0
            const char* type_start = line + 1;
14679
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
14680
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
14681
0
            if (!type_end || !name_start)
14682
0
                continue;
14683
0
            *type_end = 0; // Overwrite first ']'
14684
0
            name_start++;  // Skip second '['
14685
0
            entry_handler = FindSettingsHandler(type_start);
14686
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
14687
0
        }
14688
0
        else if (entry_handler != NULL && entry_data != NULL)
14689
0
        {
14690
            // Let type handler parse the line
14691
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
14692
0
        }
14693
0
    }
14694
0
    g.SettingsLoaded = true;
14695
14696
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
14697
0
    memcpy(buf, ini_data, ini_size);
14698
14699
    // Call post-read handlers
14700
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14701
0
        if (handler.ApplyAllFn != NULL)
14702
0
            handler.ApplyAllFn(&g, &handler);
14703
0
}
14704
14705
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
14706
0
{
14707
0
    ImGuiContext& g = *GImGui;
14708
0
    g.SettingsDirtyTimer = 0.0f;
14709
0
    if (!ini_filename)
14710
0
        return;
14711
14712
0
    size_t ini_data_size = 0;
14713
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
14714
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
14715
0
    if (!f)
14716
0
        return;
14717
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
14718
0
    ImFileClose(f);
14719
0
}
14720
14721
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
14722
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
14723
0
{
14724
0
    ImGuiContext& g = *GImGui;
14725
0
    g.SettingsDirtyTimer = 0.0f;
14726
0
    g.SettingsIniData.Buf.resize(0);
14727
0
    g.SettingsIniData.Buf.push_back(0);
14728
0
    for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
14729
0
        handler.WriteAllFn(&g, &handler, &g.SettingsIniData);
14730
0
    if (out_size)
14731
0
        *out_size = (size_t)g.SettingsIniData.size();
14732
0
    return g.SettingsIniData.c_str();
14733
0
}
14734
14735
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
14736
0
{
14737
0
    ImGuiContext& g = *GImGui;
14738
14739
0
    if (g.IO.ConfigDebugIniSettings == false)
14740
0
    {
14741
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
14742
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
14743
0
        if (const char* p = strstr(name, "###"))
14744
0
            name = p;
14745
0
    }
14746
0
    const size_t name_len = strlen(name);
14747
14748
    // Allocate chunk
14749
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
14750
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
14751
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
14752
0
    settings->ID = ImHashStr(name, name_len);
14753
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
14754
14755
0
    return settings;
14756
0
}
14757
14758
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
14759
// This is called once per window .ini entry + once per newly instantiated window.
14760
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
14761
2
{
14762
2
    ImGuiContext& g = *GImGui;
14763
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14764
0
        if (settings->ID == id && !settings->WantDelete)
14765
0
            return settings;
14766
2
    return NULL;
14767
2
}
14768
14769
// This is faster if you are holding on a Window already as we don't need to perform a search.
14770
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
14771
2
{
14772
2
    ImGuiContext& g = *GImGui;
14773
2
    if (window->SettingsOffset != -1)
14774
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
14775
2
    return FindWindowSettingsByID(window->ID);
14776
2
}
14777
14778
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
14779
void ImGui::ClearWindowSettings(const char* name)
14780
0
{
14781
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
14782
0
    ImGuiContext& g = *GImGui;
14783
0
    ImGuiWindow* window = FindWindowByName(name);
14784
0
    if (window != NULL)
14785
0
    {
14786
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
14787
0
        InitOrLoadWindowSettings(window, NULL);
14788
0
        if (window->DockId != 0)
14789
0
            DockContextProcessUndockWindow(&g, window, true);
14790
0
    }
14791
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
14792
0
        settings->WantDelete = true;
14793
0
}
14794
14795
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14796
0
{
14797
0
    ImGuiContext& g = *ctx;
14798
0
    for (ImGuiWindow* window : g.Windows)
14799
0
        window->SettingsOffset = -1;
14800
0
    g.SettingsWindows.clear();
14801
0
}
14802
14803
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
14804
0
{
14805
0
    ImGuiID id = ImHashStr(name);
14806
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
14807
0
    if (settings)
14808
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
14809
0
    else
14810
0
        settings = ImGui::CreateNewWindowSettings(name);
14811
0
    settings->ID = id;
14812
0
    settings->WantApply = true;
14813
0
    return (void*)settings;
14814
0
}
14815
14816
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
14817
0
{
14818
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
14819
0
    int x, y;
14820
0
    int i;
14821
0
    ImU32 u1;
14822
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
14823
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
14824
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
14825
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
14826
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
14827
0
    else if (sscanf(line, "IsChild=%d", &i) == 1)           { settings->IsChild = (i != 0); }
14828
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
14829
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
14830
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
14831
0
}
14832
14833
// Apply to existing windows (if any)
14834
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
14835
0
{
14836
0
    ImGuiContext& g = *ctx;
14837
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14838
0
        if (settings->WantApply)
14839
0
        {
14840
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
14841
0
                ApplyWindowSettings(window, settings);
14842
0
            settings->WantApply = false;
14843
0
        }
14844
0
}
14845
14846
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
14847
0
{
14848
    // Gather data from windows that were active during this session
14849
    // (if a window wasn't opened in this session we preserve its settings)
14850
0
    ImGuiContext& g = *ctx;
14851
0
    for (ImGuiWindow* window : g.Windows)
14852
0
    {
14853
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
14854
0
            continue;
14855
14856
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
14857
0
        if (!settings)
14858
0
        {
14859
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
14860
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
14861
0
        }
14862
0
        IM_ASSERT(settings->ID == window->ID);
14863
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
14864
0
        settings->Size = ImVec2ih(window->SizeFull);
14865
0
        settings->ViewportId = window->ViewportId;
14866
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
14867
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
14868
0
        settings->DockId = window->DockId;
14869
0
        settings->ClassId = window->WindowClass.ClassId;
14870
0
        settings->DockOrder = window->DockOrder;
14871
0
        settings->Collapsed = window->Collapsed;
14872
0
        settings->IsChild = (window->RootWindow != window); // Cannot rely on ImGuiWindowFlags_ChildWindow here as docked windows have this set.
14873
0
        settings->WantDelete = false;
14874
0
    }
14875
14876
    // Write to text buffer
14877
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
14878
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14879
0
    {
14880
0
        if (settings->WantDelete)
14881
0
            continue;
14882
0
        const char* settings_name = settings->GetName();
14883
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
14884
0
        if (settings->IsChild)
14885
0
        {
14886
0
            buf->appendf("IsChild=1\n");
14887
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14888
0
        }
14889
0
        else
14890
0
        {
14891
0
            if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14892
0
            {
14893
0
                buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
14894
0
                buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
14895
0
            }
14896
0
            if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
14897
0
                buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
14898
0
            if (settings->Size.x != 0 || settings->Size.y != 0)
14899
0
                buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
14900
0
            buf->appendf("Collapsed=%d\n", settings->Collapsed);
14901
0
            if (settings->DockId != 0)
14902
0
            {
14903
                //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
14904
0
                if (settings->DockOrder == -1)
14905
0
                    buf->appendf("DockId=0x%08X\n", settings->DockId);
14906
0
                else
14907
0
                    buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
14908
0
                if (settings->ClassId != 0)
14909
0
                    buf->appendf("ClassId=0x%08X\n", settings->ClassId);
14910
0
            }
14911
0
        }
14912
0
        buf->append("\n");
14913
0
    }
14914
0
}
14915
14916
14917
//-----------------------------------------------------------------------------
14918
// [SECTION] LOCALIZATION
14919
//-----------------------------------------------------------------------------
14920
14921
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
14922
1
{
14923
1
    ImGuiContext& g = *GImGui;
14924
13
    for (int n = 0; n < count; n++)
14925
12
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
14926
1
}
14927
14928
14929
//-----------------------------------------------------------------------------
14930
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
14931
//-----------------------------------------------------------------------------
14932
// - GetMainViewport()
14933
// - FindViewportByID()
14934
// - FindViewportByPlatformHandle()
14935
// - SetCurrentViewport() [Internal]
14936
// - SetWindowViewport() [Internal]
14937
// - GetWindowAlwaysWantOwnViewport() [Internal]
14938
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
14939
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
14940
// - TranslateWindowsInViewport() [Internal]
14941
// - ScaleWindowsInViewport() [Internal]
14942
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
14943
// - UpdateViewportsNewFrame() [Internal]
14944
// - UpdateViewportsEndFrame() [Internal]
14945
// - AddUpdateViewport() [Internal]
14946
// - WindowSelectViewport() [Internal]
14947
// - WindowSyncOwnedViewport() [Internal]
14948
// - UpdatePlatformWindows()
14949
// - RenderPlatformWindowsDefault()
14950
// - FindPlatformMonitorForPos() [Internal]
14951
// - FindPlatformMonitorForRect() [Internal]
14952
// - UpdateViewportPlatformMonitor() [Internal]
14953
// - DestroyPlatformWindow() [Internal]
14954
// - DestroyPlatformWindows()
14955
//-----------------------------------------------------------------------------
14956
14957
ImGuiViewport* ImGui::GetMainViewport()
14958
347k
{
14959
347k
    ImGuiContext& g = *GImGui;
14960
347k
    return g.Viewports[0];
14961
347k
}
14962
14963
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
14964
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
14965
80.5k
{
14966
80.5k
    ImGuiContext& g = *GImGui;
14967
80.5k
    for (ImGuiViewportP* viewport : g.Viewports)
14968
80.5k
        if (viewport->ID == id)
14969
80.5k
            return viewport;
14970
0
    return NULL;
14971
80.5k
}
14972
14973
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
14974
0
{
14975
0
    ImGuiContext& g = *GImGui;
14976
0
    for (ImGuiViewportP* viewport : g.Viewports)
14977
0
        if (viewport->PlatformHandle == platform_handle)
14978
0
            return viewport;
14979
0
    return NULL;
14980
0
}
14981
14982
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
14983
372k
{
14984
372k
    ImGuiContext& g = *GImGui;
14985
372k
    (void)current_window;
14986
14987
372k
    if (viewport)
14988
292k
        viewport->LastFrameActive = g.FrameCount;
14989
372k
    if (g.CurrentViewport == viewport)
14990
211k
        return;
14991
161k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14992
161k
    g.CurrentViewport = viewport;
14993
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14994
14995
    // Notify platform layer of viewport changes
14996
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14997
161k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14998
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14999
161k
}
15000
15001
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15002
186k
{
15003
    // Abandon viewport
15004
186k
    if (window->ViewportOwned && window->Viewport->Window == window)
15005
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
15006
15007
186k
    window->Viewport = viewport;
15008
186k
    window->ViewportId = viewport->ID;
15009
186k
    window->ViewportOwned = (viewport->Window == window);
15010
186k
}
15011
15012
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
15013
0
{
15014
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
15015
0
    ImGuiContext& g = *GImGui;
15016
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
15017
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15018
0
            if (!window->DockIsActive)
15019
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
15020
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
15021
0
                        return true;
15022
0
    return false;
15023
0
}
15024
15025
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
15026
0
{
15027
0
    ImGuiContext& g = *GImGui;
15028
0
    if (window->Viewport == viewport)
15029
0
        return false;
15030
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
15031
0
        return false;
15032
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
15033
0
        return false;
15034
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
15035
0
        return false;
15036
0
    if (GetWindowAlwaysWantOwnViewport(window))
15037
0
        return false;
15038
15039
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
15040
0
    for (ImGuiWindow* window_behind : g.Windows)
15041
0
    {
15042
0
        if (window_behind == window)
15043
0
            break;
15044
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
15045
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
15046
0
                return false;
15047
0
    }
15048
15049
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
15050
0
    ImGuiViewportP* old_viewport = window->Viewport;
15051
0
    if (window->ViewportOwned)
15052
0
        for (int n = 0; n < g.Windows.Size; n++)
15053
0
            if (g.Windows[n]->Viewport == old_viewport)
15054
0
                SetWindowViewport(g.Windows[n], viewport);
15055
0
    SetWindowViewport(window, viewport);
15056
0
    BringWindowToDisplayFront(window);
15057
15058
0
    return true;
15059
0
}
15060
15061
// FIXME: handle 0 to N host viewports
15062
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
15063
0
{
15064
0
    ImGuiContext& g = *GImGui;
15065
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
15066
0
}
15067
15068
// Translate Dear ImGui windows when a Host Viewport has been moved
15069
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15070
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
15071
0
{
15072
0
    ImGuiContext& g = *GImGui;
15073
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
15074
15075
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
15076
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
15077
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
15078
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
15079
    // and so the window will appear to teleport when releasing the mouse.
15080
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
15081
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
15082
0
    ImVec2 delta_pos = new_pos - old_pos;
15083
0
    for (ImGuiWindow* window : g.Windows) // FIXME-OPT
15084
0
        if (translate_all_windows || (window->Viewport == viewport && test_still_fit_rect.Contains(window->Rect())))
15085
0
            TranslateWindow(window, delta_pos);
15086
0
}
15087
15088
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
15089
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
15090
0
{
15091
0
    ImGuiContext& g = *GImGui;
15092
0
    if (viewport->Window)
15093
0
    {
15094
0
        ScaleWindow(viewport->Window, scale);
15095
0
    }
15096
0
    else
15097
0
    {
15098
0
        for (ImGuiWindow* window : g.Windows)
15099
0
            if (window->Viewport == viewport)
15100
0
                ScaleWindow(window, scale);
15101
0
    }
15102
0
}
15103
15104
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
15105
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15106
// B) It requires Platform_GetWindowFocus to be implemented by backend.
15107
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
15108
0
{
15109
0
    ImGuiContext& g = *GImGui;
15110
0
    ImGuiViewportP* best_candidate = NULL;
15111
0
    for (ImGuiViewportP* viewport : g.Viewports)
15112
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
15113
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
15114
0
                best_candidate = viewport;
15115
0
    return best_candidate;
15116
0
}
15117
15118
// Update viewports and monitor infos
15119
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
15120
static void ImGui::UpdateViewportsNewFrame()
15121
80.5k
{
15122
80.5k
    ImGuiContext& g = *GImGui;
15123
80.5k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
15124
15125
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
15126
    // Update Focused status
15127
80.5k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
15128
80.5k
    if (viewports_enabled)
15129
0
    {
15130
0
        ImGuiViewportP* focused_viewport = NULL;
15131
0
        for (ImGuiViewportP* viewport : g.Viewports)
15132
0
        {
15133
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
15134
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
15135
0
            {
15136
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
15137
0
                if (is_minimized)
15138
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
15139
0
                else
15140
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
15141
0
            }
15142
15143
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
15144
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
15145
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
15146
0
            {
15147
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
15148
0
                if (is_focused)
15149
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
15150
0
                else
15151
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
15152
0
                if (is_focused)
15153
0
                    focused_viewport = viewport;
15154
0
            }
15155
0
        }
15156
15157
        // Focused viewport has changed?
15158
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
15159
0
        {
15160
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
15161
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
15162
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
15163
15164
            // Store a tag so we can infer z-order easily from all our windows
15165
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
15166
            // will keep the front most stamp instead of losing it back to their parent viewport.
15167
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15168
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15169
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
15170
15171
            // Focus associated dear imgui window
15172
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
15173
            // - if focus didn't happen because we destroyed another window (#6462)
15174
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
15175
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
15176
0
            if (apply_imgui_focus_on_focused_viewport)
15177
0
            {
15178
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
15179
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
15180
0
                if (focused_viewport->Window != NULL)
15181
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
15182
0
                else if (focused_viewport->LastFocusedHadNavWindow)
15183
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
15184
0
                else
15185
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
15186
0
            }
15187
0
        }
15188
0
        if (focused_viewport)
15189
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
15190
0
    }
15191
15192
    // Create/update main viewport with current platform position.
15193
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
15194
80.5k
    ImGuiViewportP* main_viewport = g.Viewports[0];
15195
80.5k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
15196
80.5k
    IM_ASSERT(main_viewport->Window == NULL);
15197
80.5k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
15198
80.5k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
15199
80.5k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
15200
0
    {
15201
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
15202
0
        main_viewport_size = main_viewport->Size;
15203
0
    }
15204
80.5k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
15205
15206
80.5k
    g.CurrentDpiScale = 0.0f;
15207
80.5k
    g.CurrentViewport = NULL;
15208
80.5k
    g.MouseViewport = NULL;
15209
161k
    for (int n = 0; n < g.Viewports.Size; n++)
15210
80.5k
    {
15211
80.5k
        ImGuiViewportP* viewport = g.Viewports[n];
15212
80.5k
        viewport->Idx = n;
15213
15214
        // Erase unused viewports
15215
80.5k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
15216
0
        {
15217
0
            DestroyViewport(viewport);
15218
0
            n--;
15219
0
            continue;
15220
0
        }
15221
15222
80.5k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
15223
80.5k
        if (viewports_enabled)
15224
0
        {
15225
            // Update Position and Size (from Platform Window to ImGui) if requested.
15226
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
15227
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
15228
0
            {
15229
                // Viewport->WorkPos and WorkSize will be updated below
15230
0
                if (viewport->PlatformRequestMove)
15231
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
15232
0
                if (viewport->PlatformRequestResize)
15233
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
15234
0
            }
15235
0
        }
15236
15237
        // Update/copy monitor info
15238
80.5k
        UpdateViewportPlatformMonitor(viewport);
15239
15240
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
15241
80.5k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
15242
80.5k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
15243
80.5k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
15244
80.5k
        viewport->UpdateWorkRect();
15245
15246
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
15247
80.5k
        viewport->Alpha = 1.0f;
15248
15249
        // Translate Dear ImGui windows when a Host Viewport has been moved
15250
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
15251
80.5k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
15252
80.5k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
15253
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
15254
15255
        // Update DPI scale
15256
80.5k
        float new_dpi_scale;
15257
80.5k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
15258
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
15259
80.5k
        else if (viewport->PlatformMonitor != -1)
15260
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15261
80.5k
        else
15262
80.5k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
15263
80.5k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
15264
0
        {
15265
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
15266
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
15267
0
                ScaleWindowsInViewport(viewport, scale_factor);
15268
            //if (viewport == GetMainViewport())
15269
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
15270
15271
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
15272
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
15273
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
15274
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
15275
            //    g.ActiveIdClickOffset = ImTrunc(g.ActiveIdClickOffset * scale_factor);
15276
0
        }
15277
80.5k
        viewport->DpiScale = new_dpi_scale;
15278
80.5k
    }
15279
15280
    // Update fallback monitor
15281
80.5k
    g.PlatformMonitorsFullWorkRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
15282
80.5k
    if (g.PlatformIO.Monitors.Size == 0)
15283
80.5k
    {
15284
80.5k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
15285
80.5k
        monitor->MainPos = main_viewport->Pos;
15286
80.5k
        monitor->MainSize = main_viewport->Size;
15287
80.5k
        monitor->WorkPos = main_viewport->WorkPos;
15288
80.5k
        monitor->WorkSize = main_viewport->WorkSize;
15289
80.5k
        monitor->DpiScale = main_viewport->DpiScale;
15290
80.5k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos);
15291
80.5k
        g.PlatformMonitorsFullWorkRect.Add(monitor->WorkPos + monitor->WorkSize);
15292
80.5k
    }
15293
0
    else
15294
0
    {
15295
0
        g.FallbackMonitor = g.PlatformIO.Monitors[0];
15296
0
    }
15297
80.5k
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
15298
0
    {
15299
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos);
15300
0
        g.PlatformMonitorsFullWorkRect.Add(monitor.WorkPos + monitor.WorkSize);
15301
0
    }
15302
15303
80.5k
    if (!viewports_enabled)
15304
80.5k
    {
15305
80.5k
        g.MouseViewport = main_viewport;
15306
80.5k
        return;
15307
80.5k
    }
15308
15309
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
15310
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
15311
0
    ImGuiViewportP* viewport_hovered = NULL;
15312
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
15313
0
    {
15314
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
15315
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15316
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
15317
0
    }
15318
0
    else
15319
0
    {
15320
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
15321
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
15322
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
15323
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
15324
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
15325
0
    }
15326
0
    if (viewport_hovered != NULL)
15327
0
        g.MouseLastHoveredViewport = viewport_hovered;
15328
0
    else if (g.MouseLastHoveredViewport == NULL)
15329
0
        g.MouseLastHoveredViewport = g.Viewports[0];
15330
15331
    // Update mouse reference viewport
15332
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
15333
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
15334
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
15335
0
        g.MouseViewport = g.MovingWindow->Viewport;
15336
0
    else
15337
0
        g.MouseViewport = g.MouseLastHoveredViewport;
15338
15339
    // When dragging something, always refer to the last hovered viewport.
15340
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
15341
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
15342
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
15343
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
15344
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
15345
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
15346
0
        viewport_hovered = g.MouseLastHoveredViewport;
15347
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
15348
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
15349
0
            g.MouseViewport = viewport_hovered;
15350
15351
0
    IM_ASSERT(g.MouseViewport != NULL);
15352
0
}
15353
15354
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
15355
static void ImGui::UpdateViewportsEndFrame()
15356
80.5k
{
15357
80.5k
    ImGuiContext& g = *GImGui;
15358
80.5k
    g.PlatformIO.Viewports.resize(0);
15359
161k
    for (int i = 0; i < g.Viewports.Size; i++)
15360
80.5k
    {
15361
80.5k
        ImGuiViewportP* viewport = g.Viewports[i];
15362
80.5k
        viewport->LastPos = viewport->Pos;
15363
80.5k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
15364
0
            if (i > 0) // Always include main viewport in the list
15365
0
                continue;
15366
80.5k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
15367
0
            continue;
15368
80.5k
        if (i > 0)
15369
80.5k
            IM_ASSERT(viewport->Window != NULL);
15370
80.5k
        g.PlatformIO.Viewports.push_back(viewport);
15371
80.5k
    }
15372
80.5k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
15373
80.5k
}
15374
15375
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
15376
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
15377
80.5k
{
15378
80.5k
    ImGuiContext& g = *GImGui;
15379
80.5k
    IM_ASSERT(id != 0);
15380
15381
80.5k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
15382
80.5k
    if (window != NULL)
15383
0
    {
15384
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
15385
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
15386
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
15387
0
            flags |= ImGuiViewportFlags_NoInputs;
15388
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
15389
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15390
0
    }
15391
15392
80.5k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
15393
80.5k
    if (viewport)
15394
80.5k
    {
15395
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
15396
80.5k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15397
80.5k
            viewport->Pos = pos;
15398
80.5k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
15399
80.5k
            viewport->Size = size;
15400
80.5k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
15401
80.5k
    }
15402
0
    else
15403
0
    {
15404
        // New viewport
15405
0
        viewport = IM_NEW(ImGuiViewportP)();
15406
0
        viewport->ID = id;
15407
0
        viewport->Idx = g.Viewports.Size;
15408
0
        viewport->Pos = viewport->LastPos = pos;
15409
0
        viewport->Size = size;
15410
0
        viewport->Flags = flags;
15411
0
        UpdateViewportPlatformMonitor(viewport);
15412
0
        g.Viewports.push_back(viewport);
15413
0
        g.ViewportCreatedCount++;
15414
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
15415
15416
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
15417
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
15418
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
15419
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
15420
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
15421
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
15422
15423
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
15424
        // This is so we can select an appropriate font size on the first frame of our window lifetime
15425
0
        if (viewport->PlatformMonitor != -1)
15426
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
15427
0
    }
15428
15429
80.5k
    viewport->Window = window;
15430
80.5k
    viewport->LastFrameActive = g.FrameCount;
15431
80.5k
    viewport->UpdateWorkRect();
15432
80.5k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
15433
15434
80.5k
    if (window != NULL)
15435
0
        window->ViewportOwned = true;
15436
15437
80.5k
    return viewport;
15438
80.5k
}
15439
15440
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
15441
0
{
15442
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
15443
0
    ImGuiContext& g = *GImGui;
15444
0
    for (ImGuiWindow* window : g.Windows)
15445
0
    {
15446
0
        if (window->Viewport != viewport)
15447
0
            continue;
15448
0
        window->Viewport = NULL;
15449
0
        window->ViewportOwned = false;
15450
0
    }
15451
0
    if (viewport == g.MouseLastHoveredViewport)
15452
0
        g.MouseLastHoveredViewport = NULL;
15453
15454
    // Destroy
15455
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15456
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
15457
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
15458
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
15459
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
15460
0
    IM_DELETE(viewport);
15461
0
}
15462
15463
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
15464
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
15465
186k
{
15466
186k
    ImGuiContext& g = *GImGui;
15467
186k
    ImGuiWindowFlags flags = window->Flags;
15468
186k
    window->ViewportAllowPlatformMonitorExtend = -1;
15469
15470
    // Restore main viewport if multi-viewport is not supported by the backend
15471
186k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
15472
186k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15473
186k
    {
15474
186k
        SetWindowViewport(window, main_viewport);
15475
186k
        return;
15476
186k
    }
15477
0
    window->ViewportOwned = false;
15478
15479
    // Appearing popups reset their viewport so they can inherit again
15480
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
15481
0
    {
15482
0
        window->Viewport = NULL;
15483
0
        window->ViewportId = 0;
15484
0
    }
15485
15486
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
15487
0
    {
15488
        // By default inherit from parent window
15489
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
15490
0
            window->Viewport = window->ParentWindow->Viewport;
15491
15492
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
15493
0
        if (window->Viewport == NULL && window->ViewportId != 0)
15494
0
        {
15495
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
15496
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
15497
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
15498
0
        }
15499
0
    }
15500
15501
0
    bool lock_viewport = false;
15502
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
15503
0
    {
15504
        // Code explicitly request a viewport
15505
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
15506
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
15507
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
15508
0
        {
15509
0
            window->Viewport->Window = window;
15510
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
15511
0
        }
15512
0
        lock_viewport = true;
15513
0
    }
15514
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
15515
0
    {
15516
        // Always inherit viewport from parent window
15517
0
        if (window->DockNode && window->DockNode->HostWindow)
15518
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
15519
0
        window->Viewport = window->ParentWindow->Viewport;
15520
0
    }
15521
0
    else if (window->DockNode && window->DockNode->HostWindow)
15522
0
    {
15523
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
15524
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
15525
0
    }
15526
0
    else if (flags & ImGuiWindowFlags_Tooltip)
15527
0
    {
15528
0
        window->Viewport = g.MouseViewport;
15529
0
    }
15530
0
    else if (GetWindowAlwaysWantOwnViewport(window))
15531
0
    {
15532
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15533
0
    }
15534
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
15535
0
    {
15536
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
15537
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15538
0
    }
15539
0
    else
15540
0
    {
15541
        // Merge into host viewport?
15542
        // We cannot test window->ViewportOwned as it set lower in the function.
15543
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
15544
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
15545
0
        if (try_to_merge_into_host_viewport)
15546
0
            UpdateTryMergeWindowIntoHostViewports(window);
15547
0
    }
15548
15549
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
15550
0
    if (window->Viewport == NULL)
15551
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
15552
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
15553
15554
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
15555
0
    if (!lock_viewport)
15556
0
    {
15557
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
15558
0
        {
15559
            // We need to take account of the possibility that mouse may become invalid.
15560
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
15561
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
15562
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
15563
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
15564
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
15565
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
15566
0
            else
15567
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15568
0
        }
15569
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
15570
0
        {
15571
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
15572
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
15573
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
15574
0
            {
15575
                // Steal/transfer ownership
15576
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
15577
0
                window->Viewport->Window = window;
15578
0
                window->Viewport->ID = window->ID;
15579
0
                window->Viewport->LastNameHash = 0;
15580
0
            }
15581
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
15582
0
            {
15583
                // New viewport
15584
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
15585
0
            }
15586
0
        }
15587
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
15588
0
        {
15589
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
15590
            // Child windows are kept contained within their parent.
15591
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
15592
0
        }
15593
0
    }
15594
15595
    // Update flags
15596
0
    window->ViewportOwned = (window == window->Viewport->Window);
15597
0
    window->ViewportId = window->Viewport->ID;
15598
15599
    // If the OS window has a title bar, hide our imgui title bar
15600
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
15601
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
15602
0
}
15603
15604
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
15605
0
{
15606
0
    ImGuiContext& g = *GImGui;
15607
15608
0
    bool viewport_rect_changed = false;
15609
15610
    // Synchronize window --> viewport in most situations
15611
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
15612
0
    if (window->Viewport->PlatformRequestMove)
15613
0
    {
15614
0
        window->Pos = window->Viewport->Pos;
15615
0
        MarkIniSettingsDirty(window);
15616
0
    }
15617
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
15618
0
    {
15619
0
        viewport_rect_changed = true;
15620
0
        window->Viewport->Pos = window->Pos;
15621
0
    }
15622
15623
0
    if (window->Viewport->PlatformRequestResize)
15624
0
    {
15625
0
        window->Size = window->SizeFull = window->Viewport->Size;
15626
0
        MarkIniSettingsDirty(window);
15627
0
    }
15628
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
15629
0
    {
15630
0
        viewport_rect_changed = true;
15631
0
        window->Viewport->Size = window->Size;
15632
0
    }
15633
0
    window->Viewport->UpdateWorkRect();
15634
15635
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
15636
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
15637
0
    if (viewport_rect_changed)
15638
0
        UpdateViewportPlatformMonitor(window->Viewport);
15639
15640
    // Update common viewport flags
15641
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
15642
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
15643
0
    ImGuiWindowFlags window_flags = window->Flags;
15644
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
15645
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
15646
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
15647
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
15648
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
15649
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
15650
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
15651
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
15652
15653
    // Not correct to set modal as topmost because:
15654
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
15655
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
15656
    //if (flags & ImGuiWindowFlags_Modal)
15657
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
15658
15659
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
15660
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
15661
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
15662
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
15663
0
    if (is_short_lived_floating_window && !is_modal)
15664
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
15665
15666
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
15667
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
15668
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
15669
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
15670
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
15671
15672
    // We can also tell the backend that clearing the platform window won't be necessary,
15673
    // as our window background is filling the viewport and we have disabled BgAlpha.
15674
    // FIXME: Work on support for per-viewport transparency (#2766)
15675
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
15676
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
15677
15678
0
    window->Viewport->Flags = viewport_flags;
15679
15680
    // Update parent viewport ID
15681
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
15682
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
15683
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
15684
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
15685
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
15686
0
    else
15687
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
15688
0
}
15689
15690
// Called by user at the end of the main loop, after EndFrame()
15691
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
15692
void ImGui::UpdatePlatformWindows()
15693
0
{
15694
0
    ImGuiContext& g = *GImGui;
15695
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
15696
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
15697
0
    g.FrameCountPlatformEnded = g.FrameCount;
15698
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
15699
0
        return;
15700
15701
    // Create/resize/destroy platform windows to match each active viewport.
15702
    // Skip the main viewport (index 0), which is always fully handled by the application!
15703
0
    for (int i = 1; i < g.Viewports.Size; i++)
15704
0
    {
15705
0
        ImGuiViewportP* viewport = g.Viewports[i];
15706
15707
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
15708
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
15709
0
        bool destroy_platform_window = false;
15710
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
15711
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
15712
0
        if (destroy_platform_window)
15713
0
        {
15714
0
            DestroyPlatformWindow(viewport);
15715
0
            continue;
15716
0
        }
15717
15718
        // New windows that appears directly in a new viewport won't always have a size on their first frame
15719
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
15720
0
            continue;
15721
15722
        // Create window
15723
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
15724
0
        if (is_new_platform_window)
15725
0
        {
15726
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15727
0
            g.PlatformIO.Platform_CreateWindow(viewport);
15728
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
15729
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
15730
0
            g.PlatformWindowsCreatedCount++;
15731
0
            viewport->LastNameHash = 0;
15732
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
15733
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
15734
0
            viewport->PlatformWindowCreated = true;
15735
0
        }
15736
15737
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
15738
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
15739
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
15740
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
15741
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
15742
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
15743
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
15744
0
        viewport->LastPlatformPos = viewport->Pos;
15745
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
15746
15747
        // Update title bar (if it changed)
15748
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
15749
0
        {
15750
0
            const char* title_begin = window_for_title->Name;
15751
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
15752
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
15753
0
            if (viewport->LastNameHash != title_hash)
15754
0
            {
15755
0
                char title_end_backup_c = *title_end;
15756
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
15757
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
15758
0
                *title_end = title_end_backup_c;
15759
0
                viewport->LastNameHash = title_hash;
15760
0
            }
15761
0
        }
15762
15763
        // Update alpha (if it changed)
15764
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
15765
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
15766
0
        viewport->LastAlpha = viewport->Alpha;
15767
15768
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
15769
0
        if (g.PlatformIO.Platform_UpdateWindow)
15770
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
15771
15772
0
        if (is_new_platform_window)
15773
0
        {
15774
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
15775
0
            if (g.FrameCount < 3)
15776
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
15777
15778
            // Show window
15779
0
            g.PlatformIO.Platform_ShowWindow(viewport);
15780
15781
            // Even without focus, we assume the window becomes front-most.
15782
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
15783
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
15784
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
15785
0
        }
15786
15787
        // Clear request flags
15788
0
        viewport->ClearRequestFlags();
15789
0
    }
15790
0
}
15791
15792
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
15793
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
15794
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
15795
//
15796
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15797
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15798
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15799
//            MyRenderFunction(platform_io.Viewports[i], my_args);
15800
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
15801
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
15802
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
15803
//
15804
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
15805
0
{
15806
    // Skip the main viewport (index 0), which is always fully handled by the application!
15807
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
15808
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15809
0
    {
15810
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15811
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15812
0
            continue;
15813
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
15814
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
15815
0
    }
15816
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
15817
0
    {
15818
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
15819
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
15820
0
            continue;
15821
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
15822
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
15823
0
    }
15824
0
}
15825
15826
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
15827
0
{
15828
0
    ImGuiContext& g = *GImGui;
15829
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
15830
0
    {
15831
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15832
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
15833
0
            return monitor_n;
15834
0
    }
15835
0
    return -1;
15836
0
}
15837
15838
// Search for the monitor with the largest intersection area with the given rectangle
15839
// We generally try to avoid searching loops but the monitor count should be very small here
15840
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
15841
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
15842
80.5k
{
15843
80.5k
    ImGuiContext& g = *GImGui;
15844
15845
80.5k
    const int monitor_count = g.PlatformIO.Monitors.Size;
15846
80.5k
    if (monitor_count <= 1)
15847
80.5k
        return monitor_count - 1;
15848
15849
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
15850
    // This is necessary for tooltips which always resize down to zero at first.
15851
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
15852
0
    int best_monitor_n = -1;
15853
0
    float best_monitor_surface = 0.001f;
15854
15855
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
15856
0
    {
15857
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
15858
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
15859
0
        if (monitor_rect.Contains(rect))
15860
0
            return monitor_n;
15861
0
        ImRect overlapping_rect = rect;
15862
0
        overlapping_rect.ClipWithFull(monitor_rect);
15863
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
15864
0
        if (overlapping_surface < best_monitor_surface)
15865
0
            continue;
15866
0
        best_monitor_surface = overlapping_surface;
15867
0
        best_monitor_n = monitor_n;
15868
0
    }
15869
0
    return best_monitor_n;
15870
0
}
15871
15872
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
15873
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
15874
80.5k
{
15875
80.5k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
15876
80.5k
}
15877
15878
// Return value is always != NULL, but don't hold on it across frames.
15879
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
15880
0
{
15881
0
    ImGuiContext& g = *GImGui;
15882
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
15883
0
    int monitor_idx = viewport->PlatformMonitor;
15884
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
15885
0
        return &g.PlatformIO.Monitors[monitor_idx];
15886
0
    return &g.FallbackMonitor;
15887
0
}
15888
15889
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
15890
0
{
15891
0
    ImGuiContext& g = *GImGui;
15892
0
    if (viewport->PlatformWindowCreated)
15893
0
    {
15894
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
15895
0
        if (g.PlatformIO.Renderer_DestroyWindow)
15896
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
15897
0
        if (g.PlatformIO.Platform_DestroyWindow)
15898
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
15899
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
15900
15901
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
15902
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
15903
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
15904
0
            viewport->PlatformWindowCreated = false;
15905
0
    }
15906
0
    else
15907
0
    {
15908
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
15909
0
    }
15910
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
15911
0
    viewport->ClearRequestFlags();
15912
0
}
15913
15914
void ImGui::DestroyPlatformWindows()
15915
0
{
15916
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
15917
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
15918
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
15919
    // code to operator a consistent manner.
15920
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
15921
    // crashing if it doesn't have data stored.
15922
0
    ImGuiContext& g = *GImGui;
15923
0
    for (ImGuiViewportP* viewport : g.Viewports)
15924
0
        DestroyPlatformWindow(viewport);
15925
0
}
15926
15927
15928
//-----------------------------------------------------------------------------
15929
// [SECTION] DOCKING
15930
//-----------------------------------------------------------------------------
15931
// Docking: Internal Types
15932
// Docking: Forward Declarations
15933
// Docking: ImGuiDockContext
15934
// Docking: ImGuiDockContext Docking/Undocking functions
15935
// Docking: ImGuiDockNode
15936
// Docking: ImGuiDockNode Tree manipulation functions
15937
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
15938
// Docking: Builder Functions
15939
// Docking: Begin/End Support Functions (called from Begin/End)
15940
// Docking: Settings
15941
//-----------------------------------------------------------------------------
15942
15943
//-----------------------------------------------------------------------------
15944
// Typical Docking call flow: (root level is generally public API):
15945
//-----------------------------------------------------------------------------
15946
// - NewFrame()                               new dear imgui frame
15947
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
15948
//    | - DockContextProcessUndockWindow()    - process one window undocking request
15949
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
15950
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
15951
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
15952
//    | - DockContextProcessDock()            - process one docking request
15953
//    | - DockNodeUpdate()
15954
//    |   - DockNodeUpdateForRootNode()
15955
//    |     - DockNodeUpdateFlagsAndCollapse()
15956
//    |     - DockNodeFindInfo()
15957
//    |   - destroy unused node or tab bar
15958
//    |   - create dock node host window
15959
//    |      - Begin() etc.
15960
//    |   - DockNodeStartMouseMovingWindow()
15961
//    |   - DockNodeTreeUpdatePosSize()
15962
//    |   - DockNodeTreeUpdateSplitter()
15963
//    |   - draw node background
15964
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
15965
//    |     - DockNodeAddTabBar()
15966
//    |     - DockNodeWindowMenuUpdate()
15967
//    |     - DockNodeCalcTabBarLayout()
15968
//    |     - BeginTabBarEx()
15969
//    |     - TabItemEx() calls
15970
//    |     - EndTabBar()
15971
//    |   - BeginDockableDragDropTarget()
15972
//    |      - DockNodeUpdate()               - recurse into child nodes...
15973
//-----------------------------------------------------------------------------
15974
// - DockSpace()                              user submit a dockspace into a window
15975
//    | Begin(Child)                          - create a child window
15976
//    | DockNodeUpdate()                      - call main dock node update function
15977
//    | End(Child)
15978
//    | ItemSize()
15979
//-----------------------------------------------------------------------------
15980
// - Begin()
15981
//    | BeginDocked()
15982
//    | BeginDockableDragDropSource()
15983
//    | BeginDockableDragDropTarget()
15984
//    | - DockNodePreviewDockRender()
15985
//-----------------------------------------------------------------------------
15986
// - EndFrame()
15987
//    | DockContextEndFrame()
15988
//-----------------------------------------------------------------------------
15989
15990
//-----------------------------------------------------------------------------
15991
// Docking: Internal Types
15992
//-----------------------------------------------------------------------------
15993
// - ImGuiDockRequestType
15994
// - ImGuiDockRequest
15995
// - ImGuiDockPreviewData
15996
// - ImGuiDockNodeSettings
15997
// - ImGuiDockContext
15998
//-----------------------------------------------------------------------------
15999
16000
enum ImGuiDockRequestType
16001
{
16002
    ImGuiDockRequestType_None = 0,
16003
    ImGuiDockRequestType_Dock,
16004
    ImGuiDockRequestType_Undock,
16005
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
16006
};
16007
16008
struct ImGuiDockRequest
16009
{
16010
    ImGuiDockRequestType    Type;
16011
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
16012
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
16013
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
16014
    ImGuiDir                DockSplitDir;
16015
    float                   DockSplitRatio;
16016
    bool                    DockSplitOuter;
16017
    ImGuiWindow*            UndockTargetWindow;
16018
    ImGuiDockNode*          UndockTargetNode;
16019
16020
    ImGuiDockRequest()
16021
0
    {
16022
0
        Type = ImGuiDockRequestType_None;
16023
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
16024
0
        DockTargetNode = UndockTargetNode = NULL;
16025
0
        DockSplitDir = ImGuiDir_None;
16026
0
        DockSplitRatio = 0.5f;
16027
0
        DockSplitOuter = false;
16028
0
    }
16029
};
16030
16031
struct ImGuiDockPreviewData
16032
{
16033
    ImGuiDockNode   FutureNode;
16034
    bool            IsDropAllowed;
16035
    bool            IsCenterAvailable;
16036
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
16037
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
16038
    ImGuiDockNode*  SplitNode;
16039
    ImGuiDir        SplitDir;
16040
    float           SplitRatio;
16041
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
16042
16043
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
16044
};
16045
16046
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
16047
struct ImGuiDockNodeSettings
16048
{
16049
    ImGuiID             ID;
16050
    ImGuiID             ParentNodeId;
16051
    ImGuiID             ParentWindowId;
16052
    ImGuiID             SelectedTabId;
16053
    signed char         SplitAxis;
16054
    char                Depth;
16055
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
16056
    ImVec2ih            Pos;
16057
    ImVec2ih            Size;
16058
    ImVec2ih            SizeRef;
16059
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
16060
};
16061
16062
//-----------------------------------------------------------------------------
16063
// Docking: Forward Declarations
16064
//-----------------------------------------------------------------------------
16065
16066
namespace ImGui
16067
{
16068
    // ImGuiDockContext
16069
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
16070
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
16071
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
16072
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
16073
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
16074
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
16075
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
16076
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
16077
16078
    // ImGuiDockNode
16079
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
16080
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16081
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
16082
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
16083
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
16084
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
16085
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
16086
    static void             DockNodeUpdate(ImGuiDockNode* node);
16087
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
16088
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
16089
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
16090
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
16091
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
16092
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
16093
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
16094
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
16095
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
16096
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
16097
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
16098
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
16099
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
16100
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
16101
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
16102
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
16103
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
16104
16105
    // ImGuiDockNode tree manipulations
16106
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
16107
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
16108
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
16109
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
16110
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
16111
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
16112
16113
    // Settings
16114
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
16115
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
16116
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
16117
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
16118
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
16119
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
16120
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
16121
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
16122
}
16123
16124
//-----------------------------------------------------------------------------
16125
// Docking: ImGuiDockContext
16126
//-----------------------------------------------------------------------------
16127
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
16128
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
16129
// At boot time only, we run a simple GC to remove nodes that have no references.
16130
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
16131
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
16132
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
16133
//-----------------------------------------------------------------------------
16134
// - DockContextInitialize()
16135
// - DockContextShutdown()
16136
// - DockContextClearNodes()
16137
// - DockContextRebuildNodes()
16138
// - DockContextNewFrameUpdateUndocking()
16139
// - DockContextNewFrameUpdateDocking()
16140
// - DockContextEndFrame()
16141
// - DockContextFindNodeByID()
16142
// - DockContextBindNodeToWindow()
16143
// - DockContextGenNodeID()
16144
// - DockContextAddNode()
16145
// - DockContextRemoveNode()
16146
// - ImGuiDockContextPruneNodeData
16147
// - DockContextPruneUnusedSettingsNodes()
16148
// - DockContextBuildNodesFromSettings()
16149
// - DockContextBuildAddWindowsToNodes()
16150
//-----------------------------------------------------------------------------
16151
16152
void ImGui::DockContextInitialize(ImGuiContext* ctx)
16153
1
{
16154
1
    ImGuiContext& g = *ctx;
16155
16156
    // Add .ini handle for persistent docking data
16157
1
    ImGuiSettingsHandler ini_handler;
16158
1
    ini_handler.TypeName = "Docking";
16159
1
    ini_handler.TypeHash = ImHashStr("Docking");
16160
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
16161
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
16162
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
16163
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
16164
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
16165
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
16166
1
    g.SettingsHandlers.push_back(ini_handler);
16167
16168
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
16169
1
}
16170
16171
void ImGui::DockContextShutdown(ImGuiContext* ctx)
16172
0
{
16173
0
    ImGuiDockContext* dc = &ctx->DockContext;
16174
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16175
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16176
0
            IM_DELETE(node);
16177
0
}
16178
16179
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
16180
0
{
16181
0
    IM_UNUSED(ctx);
16182
0
    IM_ASSERT(ctx == GImGui);
16183
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
16184
0
    DockBuilderRemoveNodeChildNodes(root_id);
16185
0
}
16186
16187
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
16188
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
16189
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
16190
0
{
16191
0
    ImGuiContext& g = *ctx;
16192
0
    ImGuiDockContext* dc = &ctx->DockContext;
16193
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
16194
0
    SaveIniSettingsToMemory();
16195
0
    ImGuiID root_id = 0; // Rebuild all
16196
0
    DockContextClearNodes(ctx, root_id, false);
16197
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
16198
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
16199
0
}
16200
16201
// Docking context update function, called by NewFrame()
16202
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
16203
80.5k
{
16204
80.5k
    ImGuiContext& g = *ctx;
16205
80.5k
    ImGuiDockContext* dc = &ctx->DockContext;
16206
80.5k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16207
0
    {
16208
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
16209
0
            DockContextClearNodes(ctx, 0, true);
16210
0
        return;
16211
0
    }
16212
16213
    // Setting NoSplit at runtime merges all nodes
16214
80.5k
    if (g.IO.ConfigDockingNoSplit)
16215
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
16216
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16217
0
                if (node->IsRootNode() && node->IsSplitNode())
16218
0
                {
16219
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
16220
                    //dc->WantFullRebuild = true;
16221
0
                }
16222
16223
    // Process full rebuild
16224
#if 0
16225
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
16226
        dc->WantFullRebuild = true;
16227
#endif
16228
80.5k
    if (dc->WantFullRebuild)
16229
0
    {
16230
0
        DockContextRebuildNodes(ctx);
16231
0
        dc->WantFullRebuild = false;
16232
0
    }
16233
16234
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
16235
80.5k
    for (ImGuiDockRequest& req : dc->Requests)
16236
0
    {
16237
0
        if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetWindow)
16238
0
            DockContextProcessUndockWindow(ctx, req.UndockTargetWindow);
16239
0
        else if (req.Type == ImGuiDockRequestType_Undock && req.UndockTargetNode)
16240
0
            DockContextProcessUndockNode(ctx, req.UndockTargetNode);
16241
0
    }
16242
80.5k
}
16243
16244
// Docking context update function, called by NewFrame()
16245
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
16246
80.5k
{
16247
80.5k
    ImGuiContext& g = *ctx;
16248
80.5k
    ImGuiDockContext* dc = &ctx->DockContext;
16249
80.5k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
16250
0
        return;
16251
16252
    // [DEBUG] Store hovered dock node.
16253
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
16254
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
16255
80.5k
    g.DebugHoveredDockNode = NULL;
16256
80.5k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
16257
8.69k
    {
16258
8.69k
        if (hovered_window->DockNodeAsHost)
16259
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
16260
8.69k
        else if (hovered_window->RootWindow->DockNode)
16261
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
16262
8.69k
    }
16263
16264
    // Process Docking requests
16265
80.5k
    for (ImGuiDockRequest& req : dc->Requests)
16266
0
        if (req.Type == ImGuiDockRequestType_Dock)
16267
0
            DockContextProcessDock(ctx, &req);
16268
80.5k
    dc->Requests.resize(0);
16269
16270
    // Create windows for each automatic docking nodes
16271
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
16272
80.5k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16273
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16274
0
            if (node->IsFloatingNode())
16275
0
                DockNodeUpdate(node);
16276
80.5k
}
16277
16278
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
16279
80.5k
{
16280
    // Draw backgrounds of node missing their window
16281
80.5k
    ImGuiContext& g = *ctx;
16282
80.5k
    ImGuiDockContext* dc = &g.DockContext;
16283
80.5k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
16284
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
16285
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
16286
0
            {
16287
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
16288
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), g.Style.DockingSeparatorSize);
16289
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16290
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
16291
0
            }
16292
80.5k
}
16293
16294
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
16295
0
{
16296
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
16297
0
}
16298
16299
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
16300
0
{
16301
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
16302
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
16303
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
16304
0
    ImGuiID id = 0x0001;
16305
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
16306
0
        id++;
16307
0
    return id;
16308
0
}
16309
16310
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
16311
0
{
16312
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
16313
0
    ImGuiContext& g = *ctx;
16314
0
    if (id == 0)
16315
0
        id = DockContextGenNodeID(ctx);
16316
0
    else
16317
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
16318
16319
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
16320
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
16321
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
16322
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
16323
0
    return node;
16324
0
}
16325
16326
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
16327
0
{
16328
0
    ImGuiContext& g = *ctx;
16329
0
    ImGuiDockContext* dc = &ctx->DockContext;
16330
16331
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
16332
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
16333
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
16334
0
    IM_ASSERT(node->Windows.Size == 0);
16335
16336
0
    if (node->HostWindow)
16337
0
        node->HostWindow->DockNodeAsHost = NULL;
16338
16339
0
    ImGuiDockNode* parent_node = node->ParentNode;
16340
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
16341
0
    if (merge)
16342
0
    {
16343
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
16344
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
16345
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
16346
0
    }
16347
0
    else
16348
0
    {
16349
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
16350
0
            if (parent_node->ChildNodes[n] == node)
16351
0
                node->ParentNode->ChildNodes[n] = NULL;
16352
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
16353
0
        IM_DELETE(node);
16354
0
    }
16355
0
}
16356
16357
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
16358
0
{
16359
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
16360
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
16361
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
16362
0
}
16363
16364
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
16365
struct ImGuiDockContextPruneNodeData
16366
{
16367
    int         CountWindows, CountChildWindows, CountChildNodes;
16368
    ImGuiID     RootId;
16369
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
16370
};
16371
16372
// Garbage collect unused nodes (run once at init time)
16373
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
16374
0
{
16375
0
    ImGuiContext& g = *ctx;
16376
0
    ImGuiDockContext* dc = &ctx->DockContext;
16377
0
    IM_ASSERT(g.Windows.Size == 0);
16378
16379
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
16380
0
    pool.Reserve(dc->NodesSettings.Size);
16381
16382
    // Count child nodes and compute RootID
16383
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16384
0
    {
16385
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16386
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
16387
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
16388
0
        if (settings->ParentNodeId)
16389
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
16390
0
    }
16391
16392
    // Count reference to dock ids from dockspaces
16393
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
16394
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16395
0
    {
16396
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16397
0
        if (settings->ParentWindowId != 0)
16398
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
16399
0
                if (window_settings->DockId)
16400
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
16401
0
                        data->CountChildNodes++;
16402
0
    }
16403
16404
    // Count reference to dock ids from window settings
16405
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
16406
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
16407
0
        if (ImGuiID dock_id = settings->DockId)
16408
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
16409
0
            {
16410
0
                data->CountWindows++;
16411
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
16412
0
                    data_root->CountChildWindows++;
16413
0
            }
16414
16415
    // Prune
16416
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
16417
0
    {
16418
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
16419
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
16420
0
        if (data->CountWindows > 1)
16421
0
            continue;
16422
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
16423
16424
0
        bool remove = false;
16425
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
16426
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
16427
0
        remove |= (data_root->CountChildWindows == 0);
16428
0
        if (remove)
16429
0
        {
16430
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
16431
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
16432
0
            settings->ID = 0;
16433
0
        }
16434
0
    }
16435
0
}
16436
16437
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
16438
0
{
16439
    // Build nodes
16440
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
16441
0
    {
16442
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
16443
0
        if (settings->ID == 0)
16444
0
            continue;
16445
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
16446
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
16447
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
16448
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
16449
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
16450
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
16451
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
16452
0
            node->ParentNode->ChildNodes[0] = node;
16453
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
16454
0
            node->ParentNode->ChildNodes[1] = node;
16455
0
        node->SelectedTabId = settings->SelectedTabId;
16456
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
16457
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
16458
16459
        // Bind host window immediately if it already exist (in case of a rebuild)
16460
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
16461
0
        char host_window_title[20];
16462
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16463
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
16464
0
    }
16465
0
}
16466
16467
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
16468
0
{
16469
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
16470
0
    ImGuiContext& g = *ctx;
16471
0
    for (ImGuiWindow* window : g.Windows)
16472
0
    {
16473
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
16474
0
            continue;
16475
0
        if (window->DockNode != NULL)
16476
0
            continue;
16477
16478
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
16479
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
16480
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
16481
0
            DockNodeAddWindow(node, window, true);
16482
0
    }
16483
0
}
16484
16485
//-----------------------------------------------------------------------------
16486
// Docking: ImGuiDockContext Docking/Undocking functions
16487
//-----------------------------------------------------------------------------
16488
// - DockContextQueueDock()
16489
// - DockContextQueueUndockWindow()
16490
// - DockContextQueueUndockNode()
16491
// - DockContextQueueNotifyRemovedNode()
16492
// - DockContextProcessDock()
16493
// - DockContextProcessUndockWindow()
16494
// - DockContextProcessUndockNode()
16495
// - DockContextCalcDropPosForDocking()
16496
//-----------------------------------------------------------------------------
16497
16498
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
16499
0
{
16500
0
    IM_ASSERT(target != payload);
16501
0
    ImGuiDockRequest req;
16502
0
    req.Type = ImGuiDockRequestType_Dock;
16503
0
    req.DockTargetWindow = target;
16504
0
    req.DockTargetNode = target_node;
16505
0
    req.DockPayload = payload;
16506
0
    req.DockSplitDir = split_dir;
16507
0
    req.DockSplitRatio = split_ratio;
16508
0
    req.DockSplitOuter = split_outer;
16509
0
    ctx->DockContext.Requests.push_back(req);
16510
0
}
16511
16512
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
16513
0
{
16514
0
    ImGuiDockRequest req;
16515
0
    req.Type = ImGuiDockRequestType_Undock;
16516
0
    req.UndockTargetWindow = window;
16517
0
    ctx->DockContext.Requests.push_back(req);
16518
0
}
16519
16520
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16521
0
{
16522
0
    ImGuiDockRequest req;
16523
0
    req.Type = ImGuiDockRequestType_Undock;
16524
0
    req.UndockTargetNode = node;
16525
0
    ctx->DockContext.Requests.push_back(req);
16526
0
}
16527
16528
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
16529
0
{
16530
0
    ImGuiDockContext* dc = &ctx->DockContext;
16531
0
    for (ImGuiDockRequest& req : dc->Requests)
16532
0
        if (req.DockTargetNode == node)
16533
0
            req.Type = ImGuiDockRequestType_None;
16534
0
}
16535
16536
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
16537
0
{
16538
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
16539
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
16540
16541
0
    ImGuiContext& g = *ctx;
16542
0
    IM_UNUSED(g);
16543
16544
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
16545
0
    ImGuiWindow* target_window = req->DockTargetWindow;
16546
0
    ImGuiDockNode* node = req->DockTargetNode;
16547
0
    if (payload_window)
16548
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
16549
0
    else
16550
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
16551
16552
    // Decide which Tab will be selected at the end of the operation
16553
0
    ImGuiID next_selected_id = 0;
16554
0
    ImGuiDockNode* payload_node = NULL;
16555
0
    if (payload_window)
16556
0
    {
16557
0
        payload_node = payload_window->DockNodeAsHost;
16558
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
16559
0
        if (payload_node && payload_node->IsLeafNode())
16560
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
16561
0
        if (payload_node == NULL)
16562
0
            next_selected_id = payload_window->TabId;
16563
0
    }
16564
16565
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
16566
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
16567
0
    if (node)
16568
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
16569
0
    if (node && target_window && node == target_window->DockNodeAsHost)
16570
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
16571
16572
    // Create new node and add existing window to it
16573
0
    if (node == NULL)
16574
0
    {
16575
0
        node = DockContextAddNode(ctx, 0);
16576
0
        node->Pos = target_window->Pos;
16577
0
        node->Size = target_window->Size;
16578
0
        if (target_window->DockNodeAsHost == NULL)
16579
0
        {
16580
0
            DockNodeAddWindow(node, target_window, true);
16581
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
16582
0
            target_window->DockIsActive = true;
16583
0
        }
16584
0
    }
16585
16586
0
    ImGuiDir split_dir = req->DockSplitDir;
16587
0
    if (split_dir != ImGuiDir_None)
16588
0
    {
16589
        // Split into two, one side will be our payload node unless we are dropping a loose window
16590
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16591
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
16592
0
        const float split_ratio = req->DockSplitRatio;
16593
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
16594
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
16595
0
        new_node->HostWindow = node->HostWindow;
16596
0
        node = new_node;
16597
0
    }
16598
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16599
16600
0
    if (node != payload_node)
16601
0
    {
16602
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
16603
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
16604
0
        {
16605
0
            DockNodeAddTabBar(node);
16606
0
            for (int n = 0; n < node->Windows.Size; n++)
16607
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16608
0
        }
16609
16610
0
        if (payload_node != NULL)
16611
0
        {
16612
            // Transfer full payload node (with 1+ child windows or child nodes)
16613
0
            if (payload_node->IsSplitNode())
16614
0
            {
16615
0
                if (node->Windows.Size > 0)
16616
0
                {
16617
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
16618
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
16619
                    // This allows us to preserve some of the underlying dock tree settings nicely.
16620
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
16621
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
16622
0
                    if (visible_node->TabBar)
16623
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
16624
0
                    DockNodeMoveWindows(node, visible_node);
16625
0
                    DockNodeMoveWindows(visible_node, node);
16626
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
16627
0
                }
16628
0
                if (node->IsCentralNode())
16629
0
                {
16630
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
16631
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
16632
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
16633
0
                    IM_ASSERT(last_focused_node != NULL);
16634
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
16635
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
16636
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
16637
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
16638
0
                    last_focused_root_node->CentralNode = last_focused_node;
16639
0
                }
16640
16641
0
                IM_ASSERT(node->Windows.Size == 0);
16642
0
                DockNodeMoveChildNodes(node, payload_node);
16643
0
            }
16644
0
            else
16645
0
            {
16646
0
                const ImGuiID payload_dock_id = payload_node->ID;
16647
0
                DockNodeMoveWindows(node, payload_node);
16648
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16649
0
            }
16650
0
            DockContextRemoveNode(ctx, payload_node, true);
16651
0
        }
16652
0
        else if (payload_window)
16653
0
        {
16654
            // Transfer single window
16655
0
            const ImGuiID payload_dock_id = payload_window->DockId;
16656
0
            node->VisibleWindow = payload_window;
16657
0
            DockNodeAddWindow(node, payload_window, true);
16658
0
            if (payload_dock_id != 0)
16659
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
16660
0
        }
16661
0
    }
16662
0
    else
16663
0
    {
16664
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
16665
0
        node->WantHiddenTabBarUpdate = true;
16666
0
    }
16667
16668
    // Update selection immediately
16669
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
16670
0
        tab_bar->NextSelectedTabId = next_selected_id;
16671
0
    MarkIniSettingsDirty();
16672
0
}
16673
16674
// Problem:
16675
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
16676
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
16677
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
16678
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
16679
// Solution:
16680
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
16681
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
16682
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
16683
0
{
16684
0
    if (ref_viewport == NULL)
16685
0
        return size;
16686
16687
0
    ImGuiContext& g = *GImGui;
16688
0
    ImVec2 max_size = ImTrunc(ref_viewport->WorkSize * 0.90f);
16689
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
16690
0
    {
16691
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
16692
0
        max_size = ImTrunc(monitor->WorkSize * 0.90f);
16693
0
    }
16694
0
    return ImMin(size, max_size);
16695
0
}
16696
16697
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
16698
0
{
16699
0
    ImGuiContext& g = *ctx;
16700
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
16701
0
    if (window->DockNode)
16702
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
16703
0
    else
16704
0
        window->DockId = 0;
16705
0
    window->Collapsed = false;
16706
0
    window->DockIsActive = false;
16707
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
16708
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
16709
16710
0
    MarkIniSettingsDirty();
16711
0
}
16712
16713
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
16714
0
{
16715
0
    ImGuiContext& g = *ctx;
16716
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
16717
0
    IM_ASSERT(node->IsLeafNode());
16718
0
    IM_ASSERT(node->Windows.Size >= 1);
16719
16720
0
    if (node->IsRootNode() || node->IsCentralNode())
16721
0
    {
16722
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
16723
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
16724
0
        new_node->Pos = node->Pos;
16725
0
        new_node->Size = node->Size;
16726
0
        new_node->SizeRef = node->SizeRef;
16727
0
        DockNodeMoveWindows(new_node, node);
16728
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
16729
0
        node = new_node;
16730
0
    }
16731
0
    else
16732
0
    {
16733
        // Otherwise extract our node and merge our sibling back into the parent node.
16734
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16735
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
16736
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
16737
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
16738
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
16739
0
        node->ParentNode = NULL;
16740
0
    }
16741
0
    for (ImGuiWindow* window : node->Windows)
16742
0
    {
16743
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16744
0
        if (window->ParentWindow)
16745
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
16746
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
16747
0
    }
16748
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16749
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
16750
0
    node->WantMouseMove = true;
16751
0
    MarkIniSettingsDirty();
16752
0
}
16753
16754
// This is mostly used for automation.
16755
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
16756
0
{
16757
0
    if (target != NULL && target_node == NULL)
16758
0
        target_node = target->DockNode;
16759
16760
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
16761
    // (which would be functionally identical) we only show the outer one. Reflect this here.
16762
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
16763
0
        split_outer = true;
16764
0
    ImGuiDockPreviewData split_data;
16765
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
16766
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
16767
0
        return false;
16768
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
16769
0
    return true;
16770
0
}
16771
16772
//-----------------------------------------------------------------------------
16773
// Docking: ImGuiDockNode
16774
//-----------------------------------------------------------------------------
16775
// - DockNodeGetTabOrder()
16776
// - DockNodeAddWindow()
16777
// - DockNodeRemoveWindow()
16778
// - DockNodeMoveChildNodes()
16779
// - DockNodeMoveWindows()
16780
// - DockNodeApplyPosSizeToWindows()
16781
// - DockNodeHideHostWindow()
16782
// - ImGuiDockNodeFindInfoResults
16783
// - DockNodeFindInfo()
16784
// - DockNodeFindWindowByID()
16785
// - DockNodeUpdateFlagsAndCollapse()
16786
// - DockNodeUpdateHasCentralNodeFlag()
16787
// - DockNodeUpdateVisibleFlag()
16788
// - DockNodeStartMouseMovingWindow()
16789
// - DockNodeUpdate()
16790
// - DockNodeUpdateWindowMenu()
16791
// - DockNodeBeginAmendTabBar()
16792
// - DockNodeEndAmendTabBar()
16793
// - DockNodeUpdateTabBar()
16794
// - DockNodeAddTabBar()
16795
// - DockNodeRemoveTabBar()
16796
// - DockNodeIsDropAllowedOne()
16797
// - DockNodeIsDropAllowed()
16798
// - DockNodeCalcTabBarLayout()
16799
// - DockNodeCalcSplitRects()
16800
// - DockNodeCalcDropRectsAndTestMousePos()
16801
// - DockNodePreviewDockSetup()
16802
// - DockNodePreviewDockRender()
16803
//-----------------------------------------------------------------------------
16804
16805
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
16806
0
{
16807
0
    ID = id;
16808
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
16809
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
16810
0
    TabBar = NULL;
16811
0
    SplitAxis = ImGuiAxis_None;
16812
16813
0
    State = ImGuiDockNodeState_Unknown;
16814
0
    LastBgColor = IM_COL32_WHITE;
16815
0
    HostWindow = VisibleWindow = NULL;
16816
0
    CentralNode = OnlyNodeWithWindows = NULL;
16817
0
    CountNodeWithWindows = 0;
16818
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
16819
0
    LastFocusedNodeId = 0;
16820
0
    SelectedTabId = 0;
16821
0
    WantCloseTabId = 0;
16822
0
    RefViewportId = 0;
16823
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
16824
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
16825
0
    IsVisible = true;
16826
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
16827
0
    IsBgDrawnThisFrame = false;
16828
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
16829
0
}
16830
16831
ImGuiDockNode::~ImGuiDockNode()
16832
0
{
16833
0
    IM_DELETE(TabBar);
16834
0
    TabBar = NULL;
16835
0
    ChildNodes[0] = ChildNodes[1] = NULL;
16836
0
}
16837
16838
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
16839
0
{
16840
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
16841
0
    if (tab_bar == NULL)
16842
0
        return -1;
16843
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
16844
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
16845
0
}
16846
16847
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
16848
0
{
16849
0
    window->Hidden = true;
16850
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
16851
0
}
16852
16853
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
16854
0
{
16855
0
    ImGuiContext& g = *GImGui; (void)g;
16856
0
    if (window->DockNode)
16857
0
    {
16858
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
16859
0
        IM_ASSERT(window->DockNode->ID != node->ID);
16860
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
16861
0
    }
16862
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
16863
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16864
16865
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
16866
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
16867
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
16868
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
16869
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
16870
16871
0
    node->Windows.push_back(window);
16872
0
    node->WantHiddenTabBarUpdate = true;
16873
0
    window->DockNode = node;
16874
0
    window->DockId = node->ID;
16875
0
    window->DockIsActive = (node->Windows.Size > 1);
16876
0
    window->DockTabWantClose = false;
16877
16878
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
16879
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
16880
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
16881
0
    {
16882
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
16883
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
16884
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
16885
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
16886
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
16887
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
16888
0
    }
16889
16890
    // Add to tab bar if requested
16891
0
    if (add_to_tab_bar)
16892
0
    {
16893
0
        if (node->TabBar == NULL)
16894
0
        {
16895
0
            DockNodeAddTabBar(node);
16896
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
16897
16898
            // Add existing windows
16899
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
16900
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
16901
0
        }
16902
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
16903
0
    }
16904
16905
0
    DockNodeUpdateVisibleFlag(node);
16906
16907
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
16908
0
    if (node->HostWindow)
16909
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
16910
0
}
16911
16912
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
16913
0
{
16914
0
    ImGuiContext& g = *GImGui;
16915
0
    IM_ASSERT(window->DockNode == node);
16916
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
16917
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
16918
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
16919
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
16920
16921
0
    window->DockNode = NULL;
16922
0
    window->DockIsActive = window->DockTabWantClose = false;
16923
0
    window->DockId = save_dock_id;
16924
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
16925
0
    if (window->ParentWindow)
16926
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
16927
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
16928
16929
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
16930
0
    {
16931
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
16932
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
16933
0
        window->Viewport = NULL;
16934
0
        window->ViewportId = 0;
16935
0
        window->ViewportOwned = false;
16936
0
        window->Hidden = true;
16937
0
    }
16938
16939
    // Remove window
16940
0
    bool erased = false;
16941
0
    for (int n = 0; n < node->Windows.Size; n++)
16942
0
        if (node->Windows[n] == window)
16943
0
        {
16944
0
            node->Windows.erase(node->Windows.Data + n);
16945
0
            erased = true;
16946
0
            break;
16947
0
        }
16948
0
    if (!erased)
16949
0
        IM_ASSERT(erased);
16950
0
    if (node->VisibleWindow == window)
16951
0
        node->VisibleWindow = NULL;
16952
16953
    // Remove tab and possibly tab bar
16954
0
    node->WantHiddenTabBarUpdate = true;
16955
0
    if (node->TabBar)
16956
0
    {
16957
0
        TabBarRemoveTab(node->TabBar, window->TabId);
16958
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
16959
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
16960
0
            DockNodeRemoveTabBar(node);
16961
0
    }
16962
16963
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
16964
0
    {
16965
        // Automatic dock node delete themselves if they are not holding at least one tab
16966
0
        DockContextRemoveNode(&g, node, true);
16967
0
        return;
16968
0
    }
16969
16970
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
16971
0
    {
16972
0
        ImGuiWindow* remaining_window = node->Windows[0];
16973
        // Note: we used to transport viewport ownership here.
16974
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
16975
0
    }
16976
16977
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
16978
0
    DockNodeUpdateVisibleFlag(node);
16979
0
}
16980
16981
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16982
0
{
16983
0
    IM_ASSERT(dst_node->Windows.Size == 0);
16984
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
16985
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
16986
0
    if (dst_node->ChildNodes[0])
16987
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
16988
0
    if (dst_node->ChildNodes[1])
16989
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
16990
0
    dst_node->SplitAxis = src_node->SplitAxis;
16991
0
    dst_node->SizeRef = src_node->SizeRef;
16992
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16993
0
}
16994
16995
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16996
0
{
16997
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16998
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16999
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
17000
0
    if (src_tab_bar != NULL)
17001
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
17002
17003
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
17004
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
17005
0
    if (move_tab_bar)
17006
0
    {
17007
0
        dst_node->TabBar = src_node->TabBar;
17008
0
        src_node->TabBar = NULL;
17009
0
    }
17010
17011
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
17012
0
    for (ImGuiWindow* window : src_node->Windows)
17013
0
    {
17014
0
        window->DockNode = NULL;
17015
0
        window->DockIsActive = false;
17016
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
17017
0
    }
17018
0
    src_node->Windows.clear();
17019
17020
0
    if (!move_tab_bar && src_node->TabBar)
17021
0
    {
17022
0
        if (dst_node->TabBar)
17023
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
17024
0
        DockNodeRemoveTabBar(src_node);
17025
0
    }
17026
0
}
17027
17028
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
17029
0
{
17030
0
    for (ImGuiWindow* window : node->Windows)
17031
0
    {
17032
0
        SetWindowPos(window, node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
17033
0
        SetWindowSize(window, node->Size, ImGuiCond_Always);
17034
0
    }
17035
0
}
17036
17037
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
17038
0
{
17039
0
    if (node->HostWindow)
17040
0
    {
17041
0
        if (node->HostWindow->DockNodeAsHost == node)
17042
0
            node->HostWindow->DockNodeAsHost = NULL;
17043
0
        node->HostWindow = NULL;
17044
0
    }
17045
17046
0
    if (node->Windows.Size == 1)
17047
0
    {
17048
0
        node->VisibleWindow = node->Windows[0];
17049
0
        node->Windows[0]->DockIsActive = false;
17050
0
    }
17051
17052
0
    if (node->TabBar)
17053
0
        DockNodeRemoveTabBar(node);
17054
0
}
17055
17056
// Search function called once by root node in DockNodeUpdate()
17057
struct ImGuiDockNodeTreeInfo
17058
{
17059
    ImGuiDockNode*      CentralNode;
17060
    ImGuiDockNode*      FirstNodeWithWindows;
17061
    int                 CountNodesWithWindows;
17062
    //ImGuiWindowClass  WindowClassForMerges;
17063
17064
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
17065
};
17066
17067
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
17068
0
{
17069
0
    if (node->Windows.Size > 0)
17070
0
    {
17071
0
        if (info->FirstNodeWithWindows == NULL)
17072
0
            info->FirstNodeWithWindows = node;
17073
0
        info->CountNodesWithWindows++;
17074
0
    }
17075
0
    if (node->IsCentralNode())
17076
0
    {
17077
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
17078
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
17079
0
        info->CentralNode = node;
17080
0
    }
17081
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
17082
0
        return;
17083
0
    if (node->ChildNodes[0])
17084
0
        DockNodeFindInfo(node->ChildNodes[0], info);
17085
0
    if (node->ChildNodes[1])
17086
0
        DockNodeFindInfo(node->ChildNodes[1], info);
17087
0
}
17088
17089
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
17090
0
{
17091
0
    IM_ASSERT(id != 0);
17092
0
    for (ImGuiWindow* window : node->Windows)
17093
0
        if (window->ID == id)
17094
0
            return window;
17095
0
    return NULL;
17096
0
}
17097
17098
// - Remove inactive windows/nodes.
17099
// - Update visibility flag.
17100
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
17101
0
{
17102
0
    ImGuiContext& g = *GImGui;
17103
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
17104
17105
    // Inherit most flags
17106
0
    if (node->ParentNode)
17107
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17108
17109
    // Recurse into children
17110
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
17111
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
17112
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
17113
0
    node->HasCentralNodeChild = false;
17114
0
    if (node->ChildNodes[0])
17115
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
17116
0
    if (node->ChildNodes[1])
17117
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
17118
17119
    // Remove inactive windows, collapse nodes
17120
    // Merge node flags overrides stored in windows
17121
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17122
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17123
0
    {
17124
0
        ImGuiWindow* window = node->Windows[window_n];
17125
0
        IM_ASSERT(window->DockNode == node);
17126
17127
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17128
0
        bool remove = false;
17129
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
17130
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
17131
0
        remove |= (window->DockTabWantClose);
17132
0
        if (remove)
17133
0
        {
17134
0
            window->DockTabWantClose = false;
17135
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
17136
0
            {
17137
0
                DockNodeHideHostWindow(node);
17138
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17139
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
17140
0
                return;
17141
0
            }
17142
0
            DockNodeRemoveWindow(node, window, node->ID);
17143
0
            window_n--;
17144
0
            continue;
17145
0
        }
17146
17147
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
17148
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
17149
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
17150
0
    }
17151
0
    node->UpdateMergedFlags();
17152
17153
    // Auto-hide tab bar option
17154
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
17155
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
17156
0
        node->WantHiddenTabBarToggle = true;
17157
0
    node->WantHiddenTabBarUpdate = false;
17158
17159
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
17160
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
17161
0
        node->WantHiddenTabBarToggle = false;
17162
17163
    // Apply toggles at a single point of the frame (here!)
17164
0
    if (node->Windows.Size > 1)
17165
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
17166
0
    else if (node->WantHiddenTabBarToggle)
17167
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
17168
0
    node->WantHiddenTabBarToggle = false;
17169
17170
0
    DockNodeUpdateVisibleFlag(node);
17171
0
}
17172
17173
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
17174
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
17175
0
{
17176
0
    node->HasCentralNodeChild = false;
17177
0
    if (node->ChildNodes[0])
17178
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
17179
0
    if (node->ChildNodes[1])
17180
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
17181
0
    if (node->IsRootNode())
17182
0
    {
17183
0
        ImGuiDockNode* mark_node = node->CentralNode;
17184
0
        while (mark_node)
17185
0
        {
17186
0
            mark_node->HasCentralNodeChild = true;
17187
0
            mark_node = mark_node->ParentNode;
17188
0
        }
17189
0
    }
17190
0
}
17191
17192
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
17193
0
{
17194
    // Update visibility flag
17195
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
17196
0
    is_visible |= (node->Windows.Size > 0);
17197
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
17198
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
17199
0
    node->IsVisible = is_visible;
17200
0
}
17201
17202
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
17203
0
{
17204
0
    ImGuiContext& g = *GImGui;
17205
0
    IM_ASSERT(node->WantMouseMove == true);
17206
0
    StartMouseMovingWindow(window);
17207
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
17208
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
17209
0
    node->WantMouseMove = false;
17210
0
}
17211
17212
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
17213
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
17214
0
{
17215
0
    DockNodeUpdateFlagsAndCollapse(node);
17216
17217
    // - Setup central node pointers
17218
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
17219
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
17220
0
    ImGuiDockNodeTreeInfo info;
17221
0
    DockNodeFindInfo(node, &info);
17222
0
    node->CentralNode = info.CentralNode;
17223
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
17224
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
17225
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
17226
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
17227
17228
    // Copy the window class from of our first window so it can be used for proper dock filtering.
17229
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
17230
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
17231
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
17232
0
    {
17233
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
17234
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
17235
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
17236
0
            {
17237
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
17238
0
                break;
17239
0
            }
17240
0
    }
17241
17242
0
    ImGuiDockNode* mark_node = node->CentralNode;
17243
0
    while (mark_node)
17244
0
    {
17245
0
        mark_node->HasCentralNodeChild = true;
17246
0
        mark_node = mark_node->ParentNode;
17247
0
    }
17248
0
}
17249
17250
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
17251
0
{
17252
    // Remove ourselves from any previous different host window
17253
    // This can happen if a user mistakenly does (see #4295 for details):
17254
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
17255
    //  - N+1: NewFrame()                   // will create floating host window for that node
17256
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
17257
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
17258
0
        node->HostWindow->DockNodeAsHost = NULL;
17259
17260
0
    host_window->DockNodeAsHost = node;
17261
0
    node->HostWindow = host_window;
17262
0
}
17263
17264
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
17265
0
{
17266
0
    ImGuiContext& g = *GImGui;
17267
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
17268
0
    node->LastFrameAlive = g.FrameCount;
17269
0
    node->IsBgDrawnThisFrame = false;
17270
17271
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
17272
0
    if (node->IsRootNode())
17273
0
        DockNodeUpdateForRootNode(node);
17274
17275
    // Remove tab bar if not needed
17276
0
    if (node->TabBar && node->IsNoTabBar())
17277
0
        DockNodeRemoveTabBar(node);
17278
17279
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
17280
0
    bool want_to_hide_host_window = false;
17281
0
    if (node->IsFloatingNode())
17282
0
    {
17283
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
17284
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
17285
0
                want_to_hide_host_window = true;
17286
0
        if (node->CountNodeWithWindows == 0)
17287
0
            want_to_hide_host_window = true;
17288
0
    }
17289
0
    if (want_to_hide_host_window)
17290
0
    {
17291
0
        if (node->Windows.Size == 1)
17292
0
        {
17293
            // Floating window pos/size is authoritative
17294
0
            ImGuiWindow* single_window = node->Windows[0];
17295
0
            node->Pos = single_window->Pos;
17296
0
            node->Size = single_window->SizeFull;
17297
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17298
17299
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
17300
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
17301
0
                FocusWindow(single_window);
17302
0
            if (node->HostWindow)
17303
0
            {
17304
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
17305
0
                single_window->Viewport = node->HostWindow->Viewport;
17306
0
                single_window->ViewportId = node->HostWindow->ViewportId;
17307
0
                if (node->HostWindow->ViewportOwned)
17308
0
                {
17309
0
                    single_window->Viewport->ID = single_window->ID;
17310
0
                    single_window->Viewport->Window = single_window;
17311
0
                    single_window->ViewportOwned = true;
17312
0
                }
17313
0
            }
17314
0
            node->RefViewportId = single_window->ViewportId;
17315
0
        }
17316
17317
0
        DockNodeHideHostWindow(node);
17318
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
17319
0
        node->WantCloseAll = false;
17320
0
        node->WantCloseTabId = 0;
17321
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
17322
0
        node->LastFrameActive = g.FrameCount;
17323
17324
0
        if (node->WantMouseMove && node->Windows.Size == 1)
17325
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
17326
0
        return;
17327
0
    }
17328
17329
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
17330
    // while the expected visible window is resizing itself.
17331
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
17332
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
17333
    //   N+0: Begin(): window created (with no known size), node is created
17334
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
17335
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
17336
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
17337
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
17338
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
17339
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
17340
0
    {
17341
0
        IM_ASSERT(node->Windows.Size > 0);
17342
0
        ImGuiWindow* ref_window = NULL;
17343
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
17344
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
17345
0
        if (ref_window == NULL)
17346
0
            ref_window = node->Windows[0];
17347
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
17348
0
        {
17349
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
17350
0
            return;
17351
0
        }
17352
0
    }
17353
17354
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17355
17356
    // Decide if the node will have a close button and a window menu button
17357
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
17358
0
    node->HasCloseButton = false;
17359
0
    for (ImGuiWindow* window : node->Windows)
17360
0
    {
17361
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
17362
0
        node->HasCloseButton |= window->HasCloseButton;
17363
0
        window->DockIsActive = (node->Windows.Size > 1);
17364
0
    }
17365
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
17366
0
        node->HasCloseButton = false;
17367
17368
    // Bind or create host window
17369
0
    ImGuiWindow* host_window = NULL;
17370
0
    bool beginned_into_host_window = false;
17371
0
    if (node->IsDockSpace())
17372
0
    {
17373
        // [Explicit root dockspace node]
17374
0
        IM_ASSERT(node->HostWindow);
17375
0
        host_window = node->HostWindow;
17376
0
    }
17377
0
    else
17378
0
    {
17379
        // [Automatic root or child nodes]
17380
0
        if (node->IsRootNode() && node->IsVisible)
17381
0
        {
17382
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17383
17384
            // Sync Pos
17385
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
17386
0
                SetNextWindowPos(ref_window->Pos);
17387
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
17388
0
                SetNextWindowPos(node->Pos);
17389
17390
            // Sync Size
17391
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17392
0
                SetNextWindowSize(ref_window->SizeFull);
17393
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
17394
0
                SetNextWindowSize(node->Size);
17395
17396
            // Sync Collapsed
17397
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
17398
0
                SetNextWindowCollapsed(ref_window->Collapsed);
17399
17400
            // Sync Viewport
17401
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
17402
0
                SetNextWindowViewport(ref_window->ViewportId);
17403
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
17404
0
                SetNextWindowViewport(node->RefViewportId);
17405
17406
0
            SetNextWindowClass(&node->WindowClass);
17407
17408
            // Begin into the host window
17409
0
            char window_label[20];
17410
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
17411
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
17412
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
17413
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
17414
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
17415
17416
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
17417
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
17418
0
            Begin(window_label, NULL, window_flags);
17419
0
            PopStyleVar();
17420
0
            beginned_into_host_window = true;
17421
17422
0
            host_window = g.CurrentWindow;
17423
0
            DockNodeSetupHostWindow(node, host_window);
17424
0
            host_window->DC.CursorPos = host_window->Pos;
17425
0
            node->Pos = host_window->Pos;
17426
0
            node->Size = host_window->Size;
17427
17428
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
17429
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
17430
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
17431
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
17432
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
17433
            // after the dock host window, losing their top-most status.
17434
0
            if (node->HostWindow->Appearing)
17435
0
                BringWindowToDisplayFront(node->HostWindow);
17436
17437
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17438
0
        }
17439
0
        else if (node->ParentNode)
17440
0
        {
17441
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
17442
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17443
0
        }
17444
0
        if (node->WantMouseMove && node->HostWindow)
17445
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
17446
0
    }
17447
0
    node->RefViewportId = 0; // Clear when we have a host window
17448
17449
    // Update focused node (the one whose title bar is highlight) within a node tree
17450
0
    if (node->IsSplitNode())
17451
0
        IM_ASSERT(node->TabBar == NULL);
17452
0
    if (node->IsRootNode())
17453
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
17454
0
            while (p_window != NULL && p_window->DockNode != NULL)
17455
0
            {
17456
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
17457
0
                if (p_node == node)
17458
0
                {
17459
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
17460
0
                    break;
17461
0
                }
17462
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
17463
0
            }
17464
17465
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
17466
0
    ImGuiDockNode* central_node = node->CentralNode;
17467
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
17468
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
17469
0
    if (central_node_hole)
17470
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
17471
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
17472
0
                central_node_hole_register_hit_test_hole = false;
17473
0
    if (central_node_hole_register_hit_test_hole)
17474
0
    {
17475
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
17476
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
17477
        // covering passthru node we'd have a gap on the edge not covered by the hole)
17478
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
17479
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
17480
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
17481
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
17482
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
17483
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
17484
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
17485
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
17486
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
17487
0
        if (central_node_hole && !hole_rect.IsInverted())
17488
0
        {
17489
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17490
0
            if (host_window->ParentWindow)
17491
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
17492
0
        }
17493
0
    }
17494
17495
    // Update position/size, process and draw resizing splitters
17496
0
    if (node->IsRootNode() && host_window)
17497
0
    {
17498
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
17499
0
        PushStyleColor(ImGuiCol_Separator, g.Style.Colors[ImGuiCol_Border]);
17500
0
        PushStyleColor(ImGuiCol_SeparatorActive, g.Style.Colors[ImGuiCol_ResizeGripActive]);
17501
0
        PushStyleColor(ImGuiCol_SeparatorHovered, g.Style.Colors[ImGuiCol_ResizeGripHovered]);
17502
0
        DockNodeTreeUpdateSplitter(node);
17503
0
        PopStyleColor(3);
17504
0
    }
17505
17506
    // Draw empty node background (currently can only be the Central Node)
17507
0
    if (host_window && node->IsEmpty() && node->IsVisible)
17508
0
    {
17509
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17510
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
17511
0
        if (node->LastBgColor != 0)
17512
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
17513
0
        node->IsBgDrawnThisFrame = true;
17514
0
    }
17515
17516
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
17517
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
17518
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
17519
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
17520
0
    if (render_dockspace_bg && node->IsVisible)
17521
0
    {
17522
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
17523
0
        if (central_node_hole)
17524
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
17525
0
        else
17526
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
17527
0
    }
17528
17529
    // Draw and populate Tab Bar
17530
0
    if (host_window)
17531
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
17532
0
    if (host_window && node->Windows.Size > 0)
17533
0
    {
17534
0
        DockNodeUpdateTabBar(node, host_window);
17535
0
    }
17536
0
    else
17537
0
    {
17538
0
        node->WantCloseAll = false;
17539
0
        node->WantCloseTabId = 0;
17540
0
        node->IsFocused = false;
17541
0
    }
17542
0
    if (node->TabBar && node->TabBar->SelectedTabId)
17543
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
17544
0
    else if (node->Windows.Size > 0)
17545
0
        node->SelectedTabId = node->Windows[0]->TabId;
17546
17547
    // Draw payload drop target
17548
0
    if (host_window && node->IsVisible)
17549
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
17550
0
            BeginDockableDragDropTarget(host_window);
17551
17552
    // We update this after DockNodeUpdateTabBar()
17553
0
    node->LastFrameActive = g.FrameCount;
17554
17555
    // Recurse into children
17556
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
17557
0
    if (host_window)
17558
0
    {
17559
0
        if (node->ChildNodes[0])
17560
0
            DockNodeUpdate(node->ChildNodes[0]);
17561
0
        if (node->ChildNodes[1])
17562
0
            DockNodeUpdate(node->ChildNodes[1]);
17563
17564
        // Render outer borders last (after the tab bar)
17565
0
        if (node->IsRootNode())
17566
0
            RenderWindowOuterBorders(host_window);
17567
0
    }
17568
17569
    // End host window
17570
0
    if (beginned_into_host_window) //-V1020
17571
0
        End();
17572
0
}
17573
17574
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
17575
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
17576
0
{
17577
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
17578
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
17579
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
17580
0
        return d;
17581
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
17582
0
}
17583
17584
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
17585
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
17586
// Custom overrides may want to decorate, group, sort entries.
17587
// Please note those are internal structures: if you copy this expect occasional breakage.
17588
// (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler)
17589
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17590
0
{
17591
0
    IM_UNUSED(ctx);
17592
0
    if (tab_bar->Tabs.Size == 1)
17593
0
    {
17594
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
17595
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
17596
0
            node->WantHiddenTabBarToggle = true;
17597
0
    }
17598
0
    else
17599
0
    {
17600
        // Display a selectable list of windows in this docking node
17601
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
17602
0
        {
17603
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17604
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
17605
0
                continue;
17606
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
17607
0
                TabBarQueueFocus(tab_bar, tab);
17608
0
            SameLine();
17609
0
            Text("   ");
17610
0
        }
17611
0
    }
17612
0
}
17613
17614
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
17615
0
{
17616
    // Try to position the menu so it is more likely to stays within the same viewport
17617
0
    ImGuiContext& g = *GImGui;
17618
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
17619
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
17620
0
    else
17621
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
17622
0
    if (BeginPopup("#WindowMenu"))
17623
0
    {
17624
0
        node->IsFocused = true;
17625
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
17626
0
        EndPopup();
17627
0
    }
17628
0
}
17629
17630
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
17631
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
17632
0
{
17633
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
17634
0
        return false;
17635
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
17636
0
        return false;
17637
0
    if (node->TabBar->ID == 0)
17638
0
        return false;
17639
0
    Begin(node->HostWindow->Name);
17640
0
    PushOverrideID(node->ID);
17641
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags);
17642
0
    IM_UNUSED(ret);
17643
0
    IM_ASSERT(ret);
17644
0
    return true;
17645
0
}
17646
17647
void ImGui::DockNodeEndAmendTabBar()
17648
0
{
17649
0
    EndTabBar();
17650
0
    PopID();
17651
0
    End();
17652
0
}
17653
17654
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
17655
0
{
17656
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
17657
0
    ImGuiContext& g = *GImGui;
17658
0
    if (g.NavWindowingTarget)
17659
0
        return (g.NavWindowingTarget->DockNode == node);
17660
17661
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
17662
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
17663
0
    {
17664
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
17665
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
17666
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
17667
0
            parent_window = parent_window->ParentWindow->RootWindow;
17668
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
17669
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
17670
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
17671
0
                return true;
17672
0
    }
17673
0
    return false;
17674
0
}
17675
17676
// Submit the tab bar corresponding to a dock node and various housekeeping details.
17677
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
17678
0
{
17679
0
    ImGuiContext& g = *GImGui;
17680
0
    ImGuiStyle& style = g.Style;
17681
17682
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
17683
0
    const bool closed_all = node->WantCloseAll && node_was_active;
17684
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
17685
0
    node->WantCloseAll = false;
17686
0
    node->WantCloseTabId = 0;
17687
17688
    // Decide if we should use a focused title bar color
17689
0
    bool is_focused = false;
17690
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17691
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
17692
0
        is_focused = true;
17693
17694
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
17695
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
17696
0
    {
17697
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
17698
0
        node->IsFocused = is_focused;
17699
0
        if (is_focused)
17700
0
            node->LastFrameFocused = g.FrameCount;
17701
0
        if (node->VisibleWindow)
17702
0
        {
17703
            // Notify root of visible window (used to display title in OS task bar)
17704
0
            if (is_focused || root_node->VisibleWindow == NULL)
17705
0
                root_node->VisibleWindow = node->VisibleWindow;
17706
0
            if (node->TabBar)
17707
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
17708
0
        }
17709
0
        return;
17710
0
    }
17711
17712
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
17713
0
    bool backup_skip_item = host_window->SkipItems;
17714
0
    if (!node->IsDockSpace())
17715
0
    {
17716
0
        host_window->SkipItems = false;
17717
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
17718
0
    }
17719
17720
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
17721
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
17722
    // as docked windows themselves will override the stack with their own root ID.
17723
0
    PushOverrideID(node->ID);
17724
0
    ImGuiTabBar* tab_bar = node->TabBar;
17725
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
17726
0
    if (tab_bar == NULL)
17727
0
    {
17728
0
        DockNodeAddTabBar(node);
17729
0
        tab_bar = node->TabBar;
17730
0
    }
17731
17732
0
    ImGuiID focus_tab_id = 0;
17733
0
    node->IsFocused = is_focused;
17734
17735
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
17736
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
17737
17738
    // In a dock node, the Collapse Button turns into the Window Menu button.
17739
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
17740
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
17741
0
    {
17742
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
17743
0
        DockNodeWindowMenuUpdate(node, tab_bar);
17744
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
17745
0
            focus_tab_id = tab_bar->NextSelectedTabId;
17746
0
        is_focused |= node->IsFocused;
17747
0
    }
17748
17749
    // Layout
17750
0
    ImRect title_bar_rect, tab_bar_rect;
17751
0
    ImVec2 window_menu_button_pos;
17752
0
    ImVec2 close_button_pos;
17753
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
17754
17755
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
17756
0
    const int tabs_count_old = tab_bar->Tabs.Size;
17757
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17758
0
    {
17759
0
        ImGuiWindow* window = node->Windows[window_n];
17760
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
17761
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
17762
0
    }
17763
17764
    // Title bar
17765
0
    if (is_focused)
17766
0
        node->LastFrameFocused = g.FrameCount;
17767
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
17768
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), g.Style.DockingSeparatorSize);
17769
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
17770
17771
    // Docking/Collapse button
17772
0
    if (has_window_menu_button)
17773
0
    {
17774
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
17775
0
            OpenPopup("#WindowMenu");
17776
0
        if (IsItemActive())
17777
0
            focus_tab_id = tab_bar->SelectedTabId;
17778
0
        if (IsItemHovered(ImGuiHoveredFlags_ForTooltip | ImGuiHoveredFlags_DelayNormal) && g.HoveredIdTimer > 0.5f)
17779
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingDragToUndockOrMoveNode));
17780
0
    }
17781
17782
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
17783
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
17784
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
17785
0
    {
17786
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
17787
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
17788
0
        tabs_unsorted_start = tab_n;
17789
0
    }
17790
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
17791
0
    {
17792
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
17793
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
17794
0
        {
17795
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
17796
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab 0x%08X '%s' Order %d\n", tab->ID, TabBarGetTabName(tab_bar, tab), tab->Window ? tab->Window->DockOrder : -1);
17797
0
        }
17798
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] SelectedTabId = 0x%08X, NavWindow->TabId = 0x%08X\n", node->SelectedTabId, g.NavWindow ? g.NavWindow->TabId : -1);
17799
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
17800
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
17801
0
    }
17802
17803
    // Apply NavWindow focus back to the tab bar
17804
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
17805
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
17806
17807
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
17808
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
17809
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
17810
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
17811
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
17812
17813
    // Begin tab bar
17814
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
17815
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;// | ImGuiTabBarFlags_FittingPolicyScroll;
17816
0
    tab_bar_flags |= ImGuiTabBarFlags_DrawSelectedOverline;
17817
0
    if (!host_window->Collapsed && is_focused)
17818
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
17819
0
    tab_bar->ID = GetID("#TabBar");
17820
0
    tab_bar->SeparatorMinX = node->Pos.x + host_window->WindowBorderSize; // Separator cover the whole node width
17821
0
    tab_bar->SeparatorMaxX = node->Pos.x + node->Size.x - host_window->WindowBorderSize;
17822
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags);
17823
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
17824
17825
    // Backup style colors
17826
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
17827
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17828
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
17829
17830
    // Submit actual tabs
17831
0
    node->VisibleWindow = NULL;
17832
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17833
0
    {
17834
0
        ImGuiWindow* window = node->Windows[window_n];
17835
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
17836
0
            continue;
17837
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
17838
0
        {
17839
0
            ImGuiTabItemFlags tab_item_flags = 0;
17840
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
17841
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
17842
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
17843
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
17844
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
17845
17846
            // Apply stored style overrides for the window
17847
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17848
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
17849
17850
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
17851
0
            bool tab_open = true;
17852
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
17853
0
            if (!tab_open)
17854
0
                node->WantCloseTabId = window->TabId;
17855
0
            if (tab_bar->VisibleTabId == window->TabId)
17856
0
                node->VisibleWindow = window;
17857
17858
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
17859
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
17860
0
            window->DockTabItemRect = g.LastItemData.Rect;
17861
17862
            // Update navigation ID on menu layer
17863
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
17864
0
                host_window->NavLastIds[1] = window->TabId;
17865
0
        }
17866
0
    }
17867
17868
    // Restore style colors
17869
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17870
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
17871
17872
    // Notify root of visible window (used to display title in OS task bar)
17873
0
    if (node->VisibleWindow)
17874
0
        if (is_focused || root_node->VisibleWindow == NULL)
17875
0
            root_node->VisibleWindow = node->VisibleWindow;
17876
17877
    // Close button (after VisibleWindow was updated)
17878
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
17879
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
17880
0
    const bool close_button_is_visible = node->HasCloseButton;
17881
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
17882
0
    if (close_button_is_visible)
17883
0
    {
17884
0
        if (!close_button_is_enabled)
17885
0
        {
17886
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
17887
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
17888
0
        }
17889
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
17890
0
        {
17891
0
            node->WantCloseAll = true;
17892
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
17893
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
17894
0
        }
17895
        //if (IsItemActive())
17896
        //    focus_tab_id = tab_bar->SelectedTabId;
17897
0
        if (!close_button_is_enabled)
17898
0
        {
17899
0
            PopStyleColor();
17900
0
            PopItemFlag();
17901
0
        }
17902
0
    }
17903
17904
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
17905
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
17906
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
17907
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
17908
0
    {
17909
        // AllowOverlap mode required for appending into dock node tab bar,
17910
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
17911
0
        bool held;
17912
0
        KeepAliveID(title_bar_id);
17913
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
17914
0
        if (g.HoveredId == title_bar_id)
17915
0
        {
17916
0
            g.LastItemData.ID = title_bar_id;
17917
0
        }
17918
0
        if (held)
17919
0
        {
17920
0
            if (IsMouseClicked(0))
17921
0
                focus_tab_id = tab_bar->SelectedTabId;
17922
17923
            // Forward moving request to selected window
17924
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
17925
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false); // Undock from tab bar empty space
17926
0
        }
17927
0
    }
17928
17929
    // Forward focus from host node to selected window
17930
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
17931
    //    focus_tab_id = tab_bar->SelectedTabId;
17932
17933
    // When clicked on a tab we requested focus to the docked child
17934
    // This overrides the value set by "forward focus from host node to selected window".
17935
0
    if (tab_bar->NextSelectedTabId)
17936
0
        focus_tab_id = tab_bar->NextSelectedTabId;
17937
17938
    // Apply navigation focus
17939
0
    if (focus_tab_id != 0)
17940
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
17941
0
            if (tab->Window)
17942
0
            {
17943
0
                FocusWindow(tab->Window);
17944
0
                NavInitWindow(tab->Window, false);
17945
0
            }
17946
17947
0
    EndTabBar();
17948
0
    PopID();
17949
17950
    // Restore SkipItems flag
17951
0
    if (!node->IsDockSpace())
17952
0
    {
17953
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
17954
0
        host_window->SkipItems = backup_skip_item;
17955
0
    }
17956
0
}
17957
17958
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
17959
0
{
17960
0
    IM_ASSERT(node->TabBar == NULL);
17961
0
    node->TabBar = IM_NEW(ImGuiTabBar);
17962
0
}
17963
17964
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
17965
0
{
17966
0
    if (node->TabBar == NULL)
17967
0
        return;
17968
0
    IM_DELETE(node->TabBar);
17969
0
    node->TabBar = NULL;
17970
0
}
17971
17972
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
17973
5
{
17974
5
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
17975
0
        return false;
17976
17977
5
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
17978
5
    ImGuiWindowClass* payload_class = &payload->WindowClass;
17979
5
    if (host_class->ClassId != payload_class->ClassId)
17980
0
    {
17981
0
        bool pass = false;
17982
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
17983
0
            pass = true;
17984
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
17985
0
            pass = true;
17986
0
        if (!pass)
17987
0
            return false;
17988
0
    }
17989
17990
    // Prevent docking any window created above a popup
17991
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
17992
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
17993
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
17994
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
17995
5
    ImGuiContext& g = *GImGui;
17996
5
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
17997
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
17998
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
17999
0
                return false;
18000
18001
5
    return true;
18002
5
}
18003
18004
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
18005
5
{
18006
5
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
18007
0
        return true;
18008
18009
5
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
18010
5
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
18011
5
    {
18012
5
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
18013
5
        if (DockNodeIsDropAllowedOne(payload, host_window))
18014
5
            return true;
18015
5
    }
18016
0
    return false;
18017
5
}
18018
18019
// window menu button == collapse button when not in a dock node.
18020
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
18021
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
18022
0
{
18023
0
    ImGuiContext& g = *GImGui;
18024
0
    ImGuiStyle& style = g.Style;
18025
18026
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
18027
0
    if (out_title_rect) { *out_title_rect = r; }
18028
18029
0
    r.Min.x += style.WindowBorderSize;
18030
0
    r.Max.x -= style.WindowBorderSize;
18031
18032
0
    float button_sz = g.FontSize;
18033
0
    r.Min.x += style.FramePadding.x;
18034
0
    r.Max.x -= style.FramePadding.x;
18035
0
    ImVec2 window_menu_button_pos = ImVec2(r.Min.x, r.Min.y + style.FramePadding.y);
18036
0
    if (node->HasCloseButton)
18037
0
    {
18038
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18039
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18040
0
    }
18041
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
18042
0
    {
18043
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
18044
0
    }
18045
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
18046
0
    {
18047
0
        window_menu_button_pos = ImVec2(r.Max.x - button_sz, r.Min.y + style.FramePadding.y);
18048
0
        r.Max.x -= button_sz + style.ItemInnerSpacing.x;
18049
0
    }
18050
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
18051
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
18052
0
}
18053
18054
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
18055
0
{
18056
0
    ImGuiContext& g = *GImGui;
18057
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
18058
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18059
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
18060
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
18061
18062
    // Distribute size on given axis (with a desired size or equally)
18063
0
    const float w_avail = size_old[axis] - dock_spacing;
18064
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
18065
0
    {
18066
0
        size_new[axis] = size_new_desired[axis];
18067
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18068
0
    }
18069
0
    else
18070
0
    {
18071
0
        size_new[axis] = IM_TRUNC(w_avail * 0.5f);
18072
0
        size_old[axis] = IM_TRUNC(w_avail - size_new[axis]);
18073
0
    }
18074
18075
    // Position each node
18076
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
18077
0
    {
18078
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
18079
0
    }
18080
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
18081
0
    {
18082
0
        pos_new[axis] = pos_old[axis];
18083
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
18084
0
    }
18085
0
}
18086
18087
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
18088
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
18089
0
{
18090
0
    ImGuiContext& g = *GImGui;
18091
18092
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
18093
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
18094
0
    float hs_w; // Half-size, longer axis
18095
0
    float hs_h; // Half-size, smaller axis
18096
0
    ImVec2 off; // Distance from edge or center
18097
0
    if (outer_docking)
18098
0
    {
18099
        //hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
18100
        //hs_h = ImTrunc(hs_w * 0.15f);
18101
        //off = ImVec2(ImTrunc(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImTrunc(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
18102
0
        hs_w = ImTrunc(hs_for_central_nodes * 1.50f);
18103
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.80f);
18104
0
        off = ImTrunc(ImVec2(parent.GetWidth() * 0.5f - hs_h, parent.GetHeight() * 0.5f - hs_h));
18105
0
    }
18106
0
    else
18107
0
    {
18108
0
        hs_w = ImTrunc(hs_for_central_nodes);
18109
0
        hs_h = ImTrunc(hs_for_central_nodes * 0.90f);
18110
0
        off = ImTrunc(ImVec2(hs_w * 2.40f, hs_w * 2.40f));
18111
0
    }
18112
18113
0
    ImVec2 c = ImTrunc(parent.GetCenter());
18114
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
18115
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
18116
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
18117
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
18118
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
18119
18120
0
    if (test_mouse_pos == NULL)
18121
0
        return false;
18122
18123
0
    ImRect hit_r = out_r;
18124
0
    if (!outer_docking)
18125
0
    {
18126
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
18127
0
        hit_r.Expand(ImTrunc(hs_w * 0.30f));
18128
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
18129
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
18130
0
        float r_threshold_center = hs_w * 1.4f;
18131
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
18132
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
18133
0
            return (dir == ImGuiDir_None);
18134
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
18135
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
18136
0
    }
18137
0
    return hit_r.Contains(*test_mouse_pos);
18138
0
}
18139
18140
// host_node may be NULL if the window doesn't have a DockNode already.
18141
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
18142
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
18143
0
{
18144
0
    ImGuiContext& g = *GImGui;
18145
18146
    // There is an edge case when docking into a dockspace which only has inactive nodes.
18147
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
18148
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
18149
0
    if (payload_node == NULL)
18150
0
        payload_node = payload_window->DockNodeAsHost;
18151
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
18152
0
    if (ref_node_for_rect)
18153
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
18154
18155
    // Filter, figure out where we are allowed to dock
18156
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
18157
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
18158
0
    data->IsCenterAvailable = true;
18159
0
    if (is_outer_docking)
18160
0
        data->IsCenterAvailable = false;
18161
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
18162
0
        data->IsCenterAvailable = false;
18163
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverCentralNode) && host_node->IsCentralNode())
18164
0
        data->IsCenterAvailable = false;
18165
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
18166
0
        data->IsCenterAvailable = false;
18167
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
18168
0
        data->IsCenterAvailable = false;
18169
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
18170
0
        data->IsCenterAvailable = false;
18171
18172
0
    data->IsSidesAvailable = true;
18173
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplit) || g.IO.ConfigDockingNoSplit)
18174
0
        data->IsSidesAvailable = false;
18175
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
18176
0
        data->IsSidesAvailable = false;
18177
0
    else if (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther)
18178
0
        data->IsSidesAvailable = false;
18179
18180
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
18181
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
18182
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
18183
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
18184
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
18185
18186
    // Calculate drop shapes geometry for allowed splitting directions
18187
0
    IM_ASSERT(ImGuiDir_None == -1);
18188
0
    data->SplitNode = host_node;
18189
0
    data->SplitDir = ImGuiDir_None;
18190
0
    data->IsSplitDirExplicit = false;
18191
0
    if (!host_window->Collapsed)
18192
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18193
0
        {
18194
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
18195
0
                continue;
18196
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
18197
0
                continue;
18198
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
18199
0
            {
18200
0
                data->SplitDir = (ImGuiDir)dir;
18201
0
                data->IsSplitDirExplicit = true;
18202
0
            }
18203
0
        }
18204
18205
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
18206
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
18207
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
18208
0
        data->IsDropAllowed = false;
18209
18210
    // Calculate split area
18211
0
    data->SplitRatio = 0.0f;
18212
0
    if (data->SplitDir != ImGuiDir_None)
18213
0
    {
18214
0
        ImGuiDir split_dir = data->SplitDir;
18215
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
18216
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
18217
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
18218
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
18219
18220
        // Calculate split ratio so we can pass it down the docking request
18221
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
18222
0
        data->FutureNode.Pos = pos_new;
18223
0
        data->FutureNode.Size = size_new;
18224
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
18225
0
    }
18226
0
}
18227
18228
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
18229
0
{
18230
0
    ImGuiContext& g = *GImGui;
18231
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
18232
18233
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
18234
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
18235
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
18236
18237
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
18238
0
    int overlay_draw_lists_count = 0;
18239
0
    ImDrawList* overlay_draw_lists[2];
18240
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
18241
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
18242
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
18243
18244
    // Draw main preview rectangle
18245
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
18246
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
18247
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
18248
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
18249
18250
    // Display area preview
18251
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
18252
0
    if (data->IsDropAllowed)
18253
0
    {
18254
0
        ImRect overlay_rect = data->FutureNode.Rect();
18255
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
18256
0
            overlay_rect.Min.y += GetFrameHeight();
18257
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
18258
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18259
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), g.Style.DockingSeparatorSize));
18260
0
    }
18261
18262
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
18263
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
18264
0
    {
18265
        // Compute target tab bar geometry so we can locate our preview tabs
18266
0
        ImRect tab_bar_rect;
18267
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
18268
0
        ImVec2 tab_pos = tab_bar_rect.Min;
18269
0
        if (host_node && host_node->TabBar)
18270
0
        {
18271
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
18272
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
18273
0
            else
18274
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
18275
0
        }
18276
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
18277
0
        {
18278
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
18279
0
        }
18280
18281
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
18282
0
        if (root_payload->DockNodeAsHost)
18283
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
18284
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
18285
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
18286
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
18287
0
        {
18288
            // DockNode's TabBar may have non-window Tabs manually appended by user
18289
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
18290
0
            if (tab_bar_with_payload && payload_window == NULL)
18291
0
                continue;
18292
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
18293
0
                continue;
18294
18295
            // Calculate the tab bounding box for each payload window
18296
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
18297
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
18298
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
18299
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
18300
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabSelected]);
18301
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
18302
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18303
0
            {
18304
0
                ImGuiTabItemFlags tab_flags = (payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0;
18305
0
                if (!tab_bar_rect.Contains(tab_bb))
18306
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
18307
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
18308
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
18309
0
                if (!tab_bar_rect.Contains(tab_bb))
18310
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
18311
0
            }
18312
0
            PopStyleColor();
18313
0
        }
18314
0
    }
18315
18316
    // Display drop boxes
18317
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
18318
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
18319
0
    {
18320
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
18321
0
        {
18322
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
18323
0
            ImRect draw_r_in = draw_r;
18324
0
            draw_r_in.Expand(-2.0f);
18325
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
18326
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
18327
0
            {
18328
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
18329
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
18330
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
18331
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
18332
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
18333
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
18334
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
18335
0
            }
18336
0
        }
18337
18338
        // Stop after ImGuiDir_None
18339
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoDockingSplit)) || g.IO.ConfigDockingNoSplit)
18340
0
            return;
18341
0
    }
18342
0
}
18343
18344
//-----------------------------------------------------------------------------
18345
// Docking: ImGuiDockNode Tree manipulation functions
18346
//-----------------------------------------------------------------------------
18347
// - DockNodeTreeSplit()
18348
// - DockNodeTreeMerge()
18349
// - DockNodeTreeUpdatePosSize()
18350
// - DockNodeTreeUpdateSplitterFindTouchingNode()
18351
// - DockNodeTreeUpdateSplitter()
18352
// - DockNodeTreeFindFallbackLeafNode()
18353
// - DockNodeTreeFindNodeByPos()
18354
//-----------------------------------------------------------------------------
18355
18356
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
18357
0
{
18358
0
    ImGuiContext& g = *GImGui;
18359
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
18360
18361
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
18362
0
    child_0->ParentNode = parent_node;
18363
18364
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
18365
0
    child_1->ParentNode = parent_node;
18366
18367
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
18368
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
18369
0
    parent_node->ChildNodes[0] = child_0;
18370
0
    parent_node->ChildNodes[1] = child_1;
18371
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
18372
0
    parent_node->SplitAxis = split_axis;
18373
0
    parent_node->VisibleWindow = NULL;
18374
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18375
18376
0
    float size_avail = (parent_node->Size[split_axis] - g.Style.DockingSeparatorSize);
18377
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
18378
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
18379
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
18380
0
    child_0->SizeRef[split_axis] = ImTrunc(size_avail * split_ratio);
18381
0
    child_1->SizeRef[split_axis] = ImTrunc(size_avail - child_0->SizeRef[split_axis]);
18382
18383
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
18384
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
18385
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
18386
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
18387
18388
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
18389
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18390
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
18391
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18392
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18393
0
    child_0->UpdateMergedFlags();
18394
0
    child_1->UpdateMergedFlags();
18395
0
    parent_node->UpdateMergedFlags();
18396
0
    if (child_inheritor->IsCentralNode())
18397
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
18398
0
}
18399
18400
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
18401
0
{
18402
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
18403
0
    ImGuiContext& g = *GImGui;
18404
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
18405
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
18406
0
    IM_ASSERT(child_0 || child_1);
18407
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
18408
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
18409
0
    {
18410
0
        IM_ASSERT(parent_node->TabBar == NULL);
18411
0
        IM_ASSERT(parent_node->Windows.Size == 0);
18412
0
    }
18413
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
18414
18415
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
18416
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
18417
0
    if (child_0)
18418
0
    {
18419
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
18420
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
18421
0
    }
18422
0
    if (child_1)
18423
0
    {
18424
0
        DockNodeMoveWindows(parent_node, child_1);
18425
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
18426
0
    }
18427
0
    DockNodeApplyPosSizeToWindows(parent_node);
18428
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
18429
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
18430
0
    parent_node->SizeRef = backup_last_explicit_size;
18431
18432
    // Flags transfer
18433
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
18434
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18435
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
18436
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
18437
0
    parent_node->UpdateMergedFlags();
18438
18439
0
    if (child_0)
18440
0
    {
18441
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
18442
0
        IM_DELETE(child_0);
18443
0
    }
18444
0
    if (child_1)
18445
0
    {
18446
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
18447
0
        IM_DELETE(child_1);
18448
0
    }
18449
0
}
18450
18451
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
18452
// (Depth-first, Pre-Order)
18453
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
18454
0
{
18455
    // During the regular dock node update we write to all nodes.
18456
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
18457
0
    ImGuiContext& g = *GImGui;
18458
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
18459
0
    if (write_to_node)
18460
0
    {
18461
0
        node->Pos = pos;
18462
0
        node->Size = size;
18463
0
    }
18464
18465
0
    if (node->IsLeafNode())
18466
0
        return;
18467
18468
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18469
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18470
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
18471
0
    ImVec2 child_0_size = size, child_1_size = size;
18472
18473
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
18474
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
18475
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
18476
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
18477
18478
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
18479
0
    {
18480
0
        const float spacing = g.Style.DockingSeparatorSize;
18481
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18482
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
18483
18484
        // Size allocation policy
18485
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
18486
0
        const float size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
18487
18488
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
18489
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc()
18490
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
18491
18492
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
18493
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
18494
0
        {
18495
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
18496
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18497
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18498
0
        }
18499
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
18500
0
        {
18501
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
18502
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
18503
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18504
0
        }
18505
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
18506
0
        {
18507
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
18508
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
18509
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
18510
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImTrunc(size_avail * split_ratio);
18511
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
18512
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
18513
0
        }
18514
18515
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
18516
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
18517
0
        {
18518
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
18519
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18520
0
        }
18521
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
18522
0
        {
18523
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
18524
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
18525
0
        }
18526
0
        else
18527
0
        {
18528
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
18529
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
18530
0
            child_0_size[axis] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5f));
18531
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
18532
0
        }
18533
18534
0
        child_1_pos[axis] += spacing + child_0_size[axis];
18535
0
    }
18536
18537
0
    if (only_write_to_single_node == NULL)
18538
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
18539
18540
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
18541
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
18542
0
    if (child_0_recurse)
18543
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
18544
0
    if (child_1_recurse)
18545
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
18546
0
}
18547
18548
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
18549
0
{
18550
0
    if (node->IsLeafNode())
18551
0
    {
18552
0
        touching_nodes->push_back(node);
18553
0
        return;
18554
0
    }
18555
0
    if (node->ChildNodes[0]->IsVisible)
18556
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
18557
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
18558
0
    if (node->ChildNodes[1]->IsVisible)
18559
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
18560
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
18561
0
}
18562
18563
// (Depth-First, Pre-Order)
18564
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
18565
0
{
18566
0
    if (node->IsLeafNode())
18567
0
        return;
18568
18569
0
    ImGuiContext& g = *GImGui;
18570
18571
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
18572
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
18573
0
    if (child_0->IsVisible && child_1->IsVisible)
18574
0
    {
18575
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
18576
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
18577
0
        IM_ASSERT(axis != ImGuiAxis_None);
18578
0
        ImRect bb;
18579
0
        bb.Min = child_0->Pos;
18580
0
        bb.Max = child_1->Pos;
18581
0
        bb.Min[axis] += child_0->Size[axis];
18582
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
18583
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
18584
18585
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
18586
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
18587
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
18588
0
        {
18589
0
            ImGuiWindow* window = g.CurrentWindow;
18590
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
18591
0
        }
18592
0
        else
18593
0
        {
18594
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
18595
            //bb.Max[axis] -= 1;
18596
0
            PushID(node->ID);
18597
18598
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
18599
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
18600
0
            float min_size = g.Style.WindowMinSize[axis];
18601
0
            float resize_limits[2];
18602
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
18603
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
18604
18605
0
            ImGuiID splitter_id = GetID("##Splitter");
18606
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
18607
0
            {
18608
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
18609
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
18610
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
18611
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
18612
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
18613
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
18614
18615
                // [DEBUG] Render touching nodes & limits
18616
                /*
18617
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18618
                for (int n = 0; n < 2; n++)
18619
                {
18620
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
18621
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
18622
                    if (axis == ImGuiAxis_X)
18623
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
18624
                    else
18625
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
18626
                }
18627
                */
18628
0
            }
18629
18630
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
18631
0
            float cur_size_0 = child_0->Size[axis];
18632
0
            float cur_size_1 = child_1->Size[axis];
18633
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
18634
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
18635
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
18636
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
18637
0
            {
18638
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
18639
0
                {
18640
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
18641
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
18642
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
18643
18644
                    // Lock the size of every node that is a sibling of the node we are touching
18645
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
18646
0
                    for (int side_n = 0; side_n < 2; side_n++)
18647
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
18648
0
                        {
18649
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
18650
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
18651
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
18652
0
                            while (touching_node->ParentNode != node)
18653
0
                            {
18654
0
                                if (touching_node->ParentNode->SplitAxis == axis)
18655
0
                                {
18656
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
18657
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
18658
0
                                    node_to_preserve->WantLockSizeOnce = true;
18659
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
18660
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
18661
0
                                }
18662
0
                                touching_node = touching_node->ParentNode;
18663
0
                            }
18664
0
                        }
18665
18666
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
18667
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
18668
0
                    MarkIniSettingsDirty();
18669
0
                }
18670
0
            }
18671
0
            PopID();
18672
0
        }
18673
0
    }
18674
18675
0
    if (child_0->IsVisible)
18676
0
        DockNodeTreeUpdateSplitter(child_0);
18677
0
    if (child_1->IsVisible)
18678
0
        DockNodeTreeUpdateSplitter(child_1);
18679
0
}
18680
18681
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
18682
0
{
18683
0
    if (node->IsLeafNode())
18684
0
        return node;
18685
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
18686
0
        return leaf_node;
18687
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
18688
0
        return leaf_node;
18689
0
    return NULL;
18690
0
}
18691
18692
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
18693
0
{
18694
0
    if (!node->IsVisible)
18695
0
        return NULL;
18696
18697
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
18698
0
    ImRect r(node->Pos, node->Pos + node->Size);
18699
0
    r.Expand(dock_spacing * 0.5f);
18700
0
    bool inside = r.Contains(pos);
18701
0
    if (!inside)
18702
0
        return NULL;
18703
18704
0
    if (node->IsLeafNode())
18705
0
        return node;
18706
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
18707
0
        return hovered_node;
18708
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
18709
0
        return hovered_node;
18710
18711
    // This means we are hovering over the splitter/spacing of a parent node
18712
0
    return node;
18713
0
}
18714
18715
//-----------------------------------------------------------------------------
18716
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
18717
//-----------------------------------------------------------------------------
18718
// - SetWindowDock() [Internal]
18719
// - DockSpace()
18720
// - DockSpaceOverViewport()
18721
//-----------------------------------------------------------------------------
18722
18723
// [Internal] Called via SetNextWindowDockID()
18724
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
18725
0
{
18726
    // Test condition (NB: bit 0 is always true) and clear flags for next time
18727
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
18728
0
        return;
18729
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
18730
18731
0
    if (window->DockId == dock_id)
18732
0
        return;
18733
18734
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
18735
0
    ImGuiContext& g = *GImGui;
18736
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(&g, dock_id))
18737
0
        if (new_node->IsSplitNode())
18738
0
        {
18739
            // Policy: Find central node or latest focused node. We first move back to our root node.
18740
0
            new_node = DockNodeGetRootNode(new_node);
18741
0
            if (new_node->CentralNode)
18742
0
            {
18743
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
18744
0
                dock_id = new_node->CentralNode->ID;
18745
0
            }
18746
0
            else
18747
0
            {
18748
0
                dock_id = new_node->LastFocusedNodeId;
18749
0
            }
18750
0
        }
18751
18752
0
    if (window->DockId == dock_id)
18753
0
        return;
18754
18755
0
    if (window->DockNode)
18756
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
18757
0
    window->DockId = dock_id;
18758
0
}
18759
18760
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
18761
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
18762
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
18763
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
18764
ImGuiID ImGui::DockSpace(ImGuiID dockspace_id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
18765
0
{
18766
0
    ImGuiContext& g = *GImGui;
18767
0
    ImGuiWindow* window = GetCurrentWindowRead();
18768
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18769
0
        return 0;
18770
18771
    // Early out if parent window is hidden/collapsed
18772
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
18773
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
18774
0
    if (window->SkipItems)
18775
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
18776
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
18777
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
18778
18779
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
18780
0
    IM_ASSERT(dockspace_id != 0);
18781
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, dockspace_id);
18782
0
    if (node == NULL)
18783
0
    {
18784
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", dockspace_id);
18785
0
        node = DockContextAddNode(&g, dockspace_id);
18786
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
18787
0
    }
18788
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
18789
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", dockspace_id, node->WindowClass.ClassId, window_class->ClassId);
18790
0
    node->SharedFlags = flags;
18791
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
18792
18793
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
18794
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
18795
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
18796
0
    {
18797
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
18798
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18799
0
        return dockspace_id;
18800
0
    }
18801
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
18802
18803
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
18804
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
18805
0
    {
18806
0
        node->LastFrameAlive = g.FrameCount;
18807
0
        return dockspace_id;
18808
0
    }
18809
18810
0
    const ImVec2 content_avail = GetContentRegionAvail();
18811
0
    ImVec2 size = ImTrunc(size_arg);
18812
0
    if (size.x <= 0.0f)
18813
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
18814
0
    if (size.y <= 0.0f)
18815
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
18816
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18817
18818
0
    node->Pos = window->DC.CursorPos;
18819
0
    node->Size = node->SizeRef = size;
18820
0
    SetNextWindowPos(node->Pos);
18821
0
    SetNextWindowSize(node->Size);
18822
0
    g.NextWindowData.PosUndock = false;
18823
18824
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
18825
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
18826
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
18827
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
18828
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
18829
0
    window_flags |= ImGuiWindowFlags_NoBackground;
18830
18831
0
    char title[256];
18832
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, dockspace_id);
18833
18834
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
18835
0
    Begin(title, NULL, window_flags);
18836
0
    PopStyleVar();
18837
18838
0
    ImGuiWindow* host_window = g.CurrentWindow;
18839
0
    DockNodeSetupHostWindow(node, host_window);
18840
0
    host_window->ChildId = window->GetID(title);
18841
0
    node->OnlyNodeWithWindows = NULL;
18842
18843
0
    IM_ASSERT(node->IsRootNode());
18844
18845
    // We need to handle the rare case were a central node is missing.
18846
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
18847
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
18848
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
18849
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
18850
    // as it doesn't make sense for an empty dockspace to not have this property.
18851
0
    if (node->IsLeafNode() && !node->IsCentralNode())
18852
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18853
18854
    // Update the node
18855
0
    DockNodeUpdate(node);
18856
18857
0
    End();
18858
18859
0
    ImRect bb(node->Pos, node->Pos + size);
18860
0
    ItemSize(size);
18861
0
    ItemAdd(bb, dockspace_id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
18862
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
18863
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
18864
18865
0
    return dockspace_id;
18866
0
}
18867
18868
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
18869
// The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar().
18870
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
18871
// If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
18872
ImGuiID ImGui::DockSpaceOverViewport(ImGuiID dockspace_id, const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
18873
0
{
18874
0
    if (viewport == NULL)
18875
0
        viewport = GetMainViewport();
18876
18877
    // Submit a window filling the entire viewport
18878
0
    SetNextWindowPos(viewport->WorkPos);
18879
0
    SetNextWindowSize(viewport->WorkSize);
18880
0
    SetNextWindowViewport(viewport->ID);
18881
18882
0
    ImGuiWindowFlags host_window_flags = 0;
18883
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
18884
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
18885
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
18886
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
18887
18888
0
    char label[32];
18889
0
    ImFormatString(label, IM_ARRAYSIZE(label), "WindowOverViewport_%08X", viewport->ID);
18890
18891
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
18892
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
18893
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
18894
0
    Begin(label, NULL, host_window_flags);
18895
0
    PopStyleVar(3);
18896
18897
    // Submit the dockspace
18898
0
    if (dockspace_id == 0)
18899
0
        dockspace_id = GetID("DockSpace");
18900
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
18901
18902
0
    End();
18903
18904
0
    return dockspace_id;
18905
0
}
18906
18907
//-----------------------------------------------------------------------------
18908
// Docking: Builder Functions
18909
//-----------------------------------------------------------------------------
18910
// Very early end-user API to manipulate dock nodes.
18911
// Only available in imgui_internal.h. Expect this API to change/break!
18912
// It is expected that those functions are all called _before_ the dockspace node submission.
18913
//-----------------------------------------------------------------------------
18914
// - DockBuilderDockWindow()
18915
// - DockBuilderGetNode()
18916
// - DockBuilderSetNodePos()
18917
// - DockBuilderSetNodeSize()
18918
// - DockBuilderAddNode()
18919
// - DockBuilderRemoveNode()
18920
// - DockBuilderRemoveNodeChildNodes()
18921
// - DockBuilderRemoveNodeDockedWindows()
18922
// - DockBuilderSplitNode()
18923
// - DockBuilderCopyNodeRec()
18924
// - DockBuilderCopyNode()
18925
// - DockBuilderCopyWindowSettings()
18926
// - DockBuilderCopyDockSpace()
18927
// - DockBuilderFinish()
18928
//-----------------------------------------------------------------------------
18929
18930
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
18931
0
{
18932
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
18933
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18934
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
18935
0
    ImGuiID window_id = ImHashStr(window_name);
18936
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
18937
0
    {
18938
        // Apply to created window
18939
0
        ImGuiID prev_node_id = window->DockId;
18940
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
18941
0
        if (window->DockId != prev_node_id)
18942
0
            window->DockOrder = -1;
18943
0
    }
18944
0
    else
18945
0
    {
18946
        // Apply to settings
18947
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
18948
0
        if (settings == NULL)
18949
0
            settings = CreateNewWindowSettings(window_name);
18950
0
        if (settings->DockId != node_id)
18951
0
            settings->DockOrder = -1;
18952
0
        settings->DockId = node_id;
18953
0
    }
18954
0
}
18955
18956
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
18957
0
{
18958
0
    ImGuiContext& g = *GImGui;
18959
0
    return DockContextFindNodeByID(&g, node_id);
18960
0
}
18961
18962
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
18963
0
{
18964
0
    ImGuiContext& g = *GImGui;
18965
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18966
0
    if (node == NULL)
18967
0
        return;
18968
0
    node->Pos = pos;
18969
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
18970
0
}
18971
18972
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
18973
0
{
18974
0
    ImGuiContext& g = *GImGui;
18975
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
18976
0
    if (node == NULL)
18977
0
        return;
18978
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
18979
0
    node->Size = node->SizeRef = size;
18980
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
18981
0
}
18982
18983
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
18984
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
18985
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
18986
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
18987
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
18988
// - Use (id == 0) to let the system allocate a node identifier.
18989
// - Existing node with a same id will be removed.
18990
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
18991
0
{
18992
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
18993
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
18994
18995
0
    if (node_id != 0)
18996
0
        DockBuilderRemoveNode(node_id);
18997
18998
0
    ImGuiDockNode* node = NULL;
18999
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
19000
0
    {
19001
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
19002
0
        node = DockContextFindNodeByID(&g, node_id);
19003
0
    }
19004
0
    else
19005
0
    {
19006
0
        node = DockContextAddNode(&g, node_id);
19007
0
        node->SetLocalFlags(flags);
19008
0
    }
19009
0
    node->LastFrameAlive = g.FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
19010
0
    return node->ID;
19011
0
}
19012
19013
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
19014
0
{
19015
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
19016
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
19017
19018
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, node_id);
19019
0
    if (node == NULL)
19020
0
        return;
19021
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
19022
0
    DockBuilderRemoveNodeChildNodes(node_id);
19023
    // Node may have moved or deleted if e.g. any merge happened
19024
0
    node = DockContextFindNodeByID(&g, node_id);
19025
0
    if (node == NULL)
19026
0
        return;
19027
0
    if (node->IsCentralNode() && node->ParentNode)
19028
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19029
0
    DockContextRemoveNode(&g, node, true);
19030
0
}
19031
19032
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
19033
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
19034
0
{
19035
0
    ImGuiContext& g = *GImGui;
19036
0
    ImGuiDockContext* dc = &g.DockContext;
19037
19038
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(&g, root_id) : NULL;
19039
0
    if (root_id && root_node == NULL)
19040
0
        return;
19041
0
    bool has_central_node = false;
19042
19043
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
19044
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
19045
19046
    // Process active windows
19047
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
19048
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19049
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19050
0
        {
19051
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
19052
0
            if (want_removal)
19053
0
            {
19054
0
                if (node->IsCentralNode())
19055
0
                    has_central_node = true;
19056
0
                if (root_id != 0)
19057
0
                    DockContextQueueNotifyRemovedNode(&g, node);
19058
0
                if (root_node)
19059
0
                {
19060
0
                    DockNodeMoveWindows(root_node, node);
19061
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
19062
0
                }
19063
0
                nodes_to_remove.push_back(node);
19064
0
            }
19065
0
        }
19066
19067
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
19068
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
19069
0
    if (root_node)
19070
0
    {
19071
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
19072
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
19073
0
    }
19074
19075
    // Apply to settings
19076
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19077
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
19078
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
19079
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
19080
0
                {
19081
0
                    settings->DockId = root_id;
19082
0
                    break;
19083
0
                }
19084
19085
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
19086
0
    if (nodes_to_remove.Size > 1)
19087
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
19088
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
19089
0
        DockContextRemoveNode(&g, nodes_to_remove[n], false);
19090
19091
0
    if (root_id == 0)
19092
0
    {
19093
0
        dc->Nodes.Clear();
19094
0
        dc->Requests.clear();
19095
0
    }
19096
0
    else if (has_central_node)
19097
0
    {
19098
0
        root_node->CentralNode = root_node;
19099
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
19100
0
    }
19101
0
}
19102
19103
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
19104
0
{
19105
    // Clear references in settings
19106
0
    ImGuiContext& g = *GImGui;
19107
0
    if (clear_settings_refs)
19108
0
    {
19109
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19110
0
        {
19111
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
19112
0
            if (!want_removal && settings->DockId != 0)
19113
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(&g, settings->DockId))
19114
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
19115
0
                        want_removal = true;
19116
0
            if (want_removal)
19117
0
                settings->DockId = 0;
19118
0
        }
19119
0
    }
19120
19121
    // Clear references in windows
19122
0
    for (int n = 0; n < g.Windows.Size; n++)
19123
0
    {
19124
0
        ImGuiWindow* window = g.Windows[n];
19125
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
19126
0
        if (want_removal)
19127
0
        {
19128
0
            const ImGuiID backup_dock_id = window->DockId;
19129
0
            IM_UNUSED(backup_dock_id);
19130
0
            DockContextProcessUndockWindow(&g, window, clear_settings_refs);
19131
0
            if (!clear_settings_refs)
19132
0
                IM_ASSERT(window->DockId == backup_dock_id);
19133
0
        }
19134
0
    }
19135
0
}
19136
19137
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
19138
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
19139
// FIXME-DOCK: We are not exposing nor using split_outer.
19140
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
19141
0
{
19142
0
    ImGuiContext& g = *GImGui;
19143
0
    IM_ASSERT(split_dir != ImGuiDir_None);
19144
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
19145
19146
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
19147
0
    if (node == NULL)
19148
0
    {
19149
0
        IM_ASSERT(node != NULL);
19150
0
        return 0;
19151
0
    }
19152
19153
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
19154
19155
0
    ImGuiDockRequest req;
19156
0
    req.Type = ImGuiDockRequestType_Split;
19157
0
    req.DockTargetWindow = NULL;
19158
0
    req.DockTargetNode = node;
19159
0
    req.DockPayload = NULL;
19160
0
    req.DockSplitDir = split_dir;
19161
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
19162
0
    req.DockSplitOuter = false;
19163
0
    DockContextProcessDock(&g, &req);
19164
19165
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
19166
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
19167
0
    if (out_id_at_dir)
19168
0
        *out_id_at_dir = id_at_dir;
19169
0
    if (out_id_at_opposite_dir)
19170
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
19171
0
    return id_at_dir;
19172
0
}
19173
19174
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
19175
0
{
19176
0
    ImGuiContext& g = *GImGui;
19177
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
19178
0
    dst_node->SharedFlags = src_node->SharedFlags;
19179
0
    dst_node->LocalFlags = src_node->LocalFlags;
19180
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
19181
0
    dst_node->Pos = src_node->Pos;
19182
0
    dst_node->Size = src_node->Size;
19183
0
    dst_node->SizeRef = src_node->SizeRef;
19184
0
    dst_node->SplitAxis = src_node->SplitAxis;
19185
0
    dst_node->UpdateMergedFlags();
19186
19187
0
    out_node_remap_pairs->push_back(src_node->ID);
19188
0
    out_node_remap_pairs->push_back(dst_node->ID);
19189
19190
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
19191
0
        if (src_node->ChildNodes[child_n])
19192
0
        {
19193
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
19194
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
19195
0
        }
19196
19197
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
19198
0
    return dst_node;
19199
0
}
19200
19201
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
19202
0
{
19203
0
    ImGuiContext& g = *GImGui;
19204
0
    IM_ASSERT(src_node_id != 0);
19205
0
    IM_ASSERT(dst_node_id != 0);
19206
0
    IM_ASSERT(out_node_remap_pairs != NULL);
19207
19208
0
    DockBuilderRemoveNode(dst_node_id);
19209
19210
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(&g, src_node_id);
19211
0
    IM_ASSERT(src_node != NULL);
19212
19213
0
    out_node_remap_pairs->clear();
19214
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
19215
19216
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
19217
0
}
19218
19219
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
19220
0
{
19221
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
19222
0
    if (src_window == NULL)
19223
0
        return;
19224
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
19225
0
    {
19226
0
        dst_window->Pos = src_window->Pos;
19227
0
        dst_window->Size = src_window->Size;
19228
0
        dst_window->SizeFull = src_window->SizeFull;
19229
0
        dst_window->Collapsed = src_window->Collapsed;
19230
0
    }
19231
0
    else
19232
0
    {
19233
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
19234
0
        if (!dst_settings)
19235
0
            dst_settings = CreateNewWindowSettings(dst_name);
19236
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
19237
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
19238
0
        {
19239
0
            dst_settings->ViewportPos = window_pos_2ih;
19240
0
            dst_settings->ViewportId = src_window->ViewportId;
19241
0
            dst_settings->Pos = ImVec2ih(0, 0);
19242
0
        }
19243
0
        else
19244
0
        {
19245
0
            dst_settings->Pos = window_pos_2ih;
19246
0
        }
19247
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
19248
0
        dst_settings->Collapsed = src_window->Collapsed;
19249
0
    }
19250
0
}
19251
19252
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
19253
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
19254
0
{
19255
0
    ImGuiContext& g = *GImGui;
19256
0
    IM_ASSERT(src_dockspace_id != 0);
19257
0
    IM_ASSERT(dst_dockspace_id != 0);
19258
0
    IM_ASSERT(in_window_remap_pairs != NULL);
19259
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
19260
19261
    // Duplicate entire dock
19262
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
19263
    // whereas we could attempt to at least keep them together in a new, same floating node.
19264
0
    ImVector<ImGuiID> node_remap_pairs;
19265
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
19266
19267
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
19268
    // (The windows associated to src_dockspace_id are staying in place)
19269
0
    ImVector<ImGuiID> src_windows;
19270
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
19271
0
    {
19272
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
19273
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
19274
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
19275
0
        src_windows.push_back(src_window_id);
19276
19277
        // Search in the remapping tables
19278
0
        ImGuiID src_dock_id = 0;
19279
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
19280
0
            src_dock_id = src_window->DockId;
19281
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
19282
0
            src_dock_id = src_window_settings->DockId;
19283
0
        ImGuiID dst_dock_id = 0;
19284
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19285
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
19286
0
            {
19287
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19288
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
19289
0
                break;
19290
0
            }
19291
19292
0
        if (dst_dock_id != 0)
19293
0
        {
19294
            // Docked windows gets redocked into the new node hierarchy.
19295
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
19296
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
19297
0
        }
19298
0
        else
19299
0
        {
19300
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
19301
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
19302
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
19303
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
19304
0
        }
19305
0
    }
19306
19307
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
19308
    // Find those windows and move to them to the cloned dock node. This may be optional?
19309
    // Dock those are a second step as undocking would invalidate source dock nodes.
19310
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
19311
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
19312
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
19313
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
19314
0
        {
19315
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
19316
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
19317
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
19318
0
            {
19319
0
                ImGuiWindow* window = node->Windows[window_n];
19320
0
                if (src_windows.contains(window->ID))
19321
0
                    continue;
19322
19323
                // Docked windows gets redocked into the new node hierarchy.
19324
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
19325
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
19326
0
            }
19327
0
        }
19328
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
19329
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
19330
0
}
19331
19332
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
19333
void ImGui::DockBuilderFinish(ImGuiID root_id)
19334
0
{
19335
0
    ImGuiContext& g = *GImGui;
19336
    //DockContextRebuild(&g);
19337
0
    DockContextBuildAddWindowsToNodes(&g, root_id);
19338
0
}
19339
19340
//-----------------------------------------------------------------------------
19341
// Docking: Begin/End Support Functions (called from Begin/End)
19342
//-----------------------------------------------------------------------------
19343
// - GetWindowAlwaysWantOwnTabBar()
19344
// - DockContextBindNodeToWindow()
19345
// - BeginDocked()
19346
// - BeginDockableDragDropSource()
19347
// - BeginDockableDragDropTarget()
19348
//-----------------------------------------------------------------------------
19349
19350
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
19351
186k
{
19352
186k
    ImGuiContext& g = *GImGui;
19353
186k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
19354
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
19355
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
19356
0
                return true;
19357
186k
    return false;
19358
186k
}
19359
19360
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
19361
0
{
19362
0
    ImGuiContext& g = *ctx;
19363
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
19364
0
    IM_ASSERT(window->DockNode == NULL);
19365
19366
    // We should not be docking into a split node (SetWindowDock should avoid this)
19367
0
    if (node && node->IsSplitNode())
19368
0
    {
19369
0
        DockContextProcessUndockWindow(ctx, window);
19370
0
        return NULL;
19371
0
    }
19372
19373
    // Create node
19374
0
    if (node == NULL)
19375
0
    {
19376
0
        node = DockContextAddNode(ctx, window->DockId);
19377
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
19378
0
        node->LastFrameAlive = g.FrameCount;
19379
0
    }
19380
19381
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
19382
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
19383
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
19384
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
19385
0
    if (!node->IsVisible)
19386
0
    {
19387
0
        ImGuiDockNode* ancestor_node = node;
19388
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
19389
0
            ancestor_node = ancestor_node->ParentNode;
19390
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
19391
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
19392
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
19393
0
    }
19394
19395
    // Add window to node
19396
0
    bool node_was_visible = node->IsVisible;
19397
0
    DockNodeAddWindow(node, window, true);
19398
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
19399
0
    IM_ASSERT(node == window->DockNode);
19400
0
    return node;
19401
0
}
19402
19403
static void StoreDockStyleForWindow(ImGuiWindow* window)
19404
3.48k
{
19405
3.48k
    ImGuiContext& g = *GImGui;
19406
31.3k
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
19407
27.8k
        window->DockStyle.Colors[color_n] = ImGui::ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
19408
3.48k
}
19409
19410
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
19411
0
{
19412
0
    ImGuiContext& g = *GImGui;
19413
19414
    // Clear fields ahead so most early-out paths don't have to do it
19415
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
19416
19417
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
19418
0
    if (auto_dock_node)
19419
0
    {
19420
0
        if (window->DockId == 0)
19421
0
        {
19422
0
            IM_ASSERT(window->DockNode == NULL);
19423
0
            window->DockId = DockContextGenNodeID(&g);
19424
0
        }
19425
0
    }
19426
0
    else
19427
0
    {
19428
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
19429
0
        bool want_undock = false;
19430
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
19431
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
19432
0
        if (want_undock)
19433
0
        {
19434
0
            DockContextProcessUndockWindow(&g, window);
19435
0
            return;
19436
0
        }
19437
0
    }
19438
19439
    // Bind to our dock node
19440
0
    ImGuiDockNode* node = window->DockNode;
19441
0
    if (node != NULL)
19442
0
        IM_ASSERT(window->DockId == node->ID);
19443
0
    if (window->DockId != 0 && node == NULL)
19444
0
    {
19445
0
        node = DockContextBindNodeToWindow(&g, window);
19446
0
        if (node == NULL)
19447
0
            return;
19448
0
    }
19449
19450
#if 0
19451
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
19452
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
19453
    {
19454
        DockContextProcessUndockWindow(ctx, window);
19455
        return;
19456
    }
19457
#endif
19458
19459
    // Undock if our dockspace node disappeared
19460
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
19461
0
    if (node->LastFrameAlive < g.FrameCount)
19462
0
    {
19463
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
19464
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
19465
0
        if (root_node->LastFrameAlive < g.FrameCount)
19466
0
            DockContextProcessUndockWindow(&g, window);
19467
0
        else
19468
0
            window->DockIsActive = true;
19469
0
        return;
19470
0
    }
19471
19472
    // Store style overrides
19473
0
    StoreDockStyleForWindow(window);
19474
19475
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
19476
    // and never create neither a host window neither a tab bar.
19477
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
19478
0
    if (node->HostWindow == NULL)
19479
0
    {
19480
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
19481
0
            window->DockIsActive = true;
19482
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
19483
0
            DockNodeHideWindowDuringHostWindowCreation(window);
19484
0
        return;
19485
0
    }
19486
19487
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
19488
0
    IM_ASSERT(node->HostWindow);
19489
0
    IM_ASSERT(node->IsLeafNode());
19490
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
19491
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
19492
19493
    // Undock if we are submitted earlier than the host window
19494
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
19495
0
    {
19496
0
        DockContextProcessUndockWindow(&g, window);
19497
0
        return;
19498
0
    }
19499
19500
    // Position/Size window
19501
0
    SetNextWindowPos(node->Pos);
19502
0
    SetNextWindowSize(node->Size);
19503
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
19504
0
    window->DockIsActive = true;
19505
0
    window->DockNodeIsVisible = true;
19506
0
    window->DockTabIsVisible = false;
19507
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
19508
0
        return;
19509
19510
    // When the window is selected we mark it as visible.
19511
0
    if (node->VisibleWindow == window)
19512
0
        window->DockTabIsVisible = true;
19513
19514
    // Update window flag
19515
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
19516
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize;
19517
0
    window->ChildFlags |= ImGuiChildFlags_AlwaysUseWindowPadding;
19518
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
19519
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
19520
0
    else
19521
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
19522
19523
    // Save new dock order only if the window has been visible once already
19524
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
19525
0
    if (node->TabBar && window->WasActive)
19526
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
19527
19528
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
19529
0
        *p_open = false;
19530
19531
    // Update ChildId to allow returning from Child to Parent with Escape
19532
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
19533
0
    window->ChildId = parent_window->GetID(window->Name);
19534
0
}
19535
19536
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
19537
4.96k
{
19538
4.96k
    ImGuiContext& g = *GImGui;
19539
4.96k
    IM_ASSERT(g.ActiveId == window->MoveId);
19540
4.96k
    IM_ASSERT(g.MovingWindow == window);
19541
4.96k
    IM_ASSERT(g.CurrentWindow == window);
19542
19543
    // 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking.
19544
4.96k
    if (g.IO.ConfigDockingWithShift != g.IO.KeyShift)
19545
0
    {
19546
        // When ConfigDockingWithShift is set, display a tooltip to increase UI affordance.
19547
        // We cannot set for HoveredWindowUnderMovingWindow != NULL here, as it is only valid/useful when drag and drop is already active
19548
        // (because of the 'is_mouse_dragging_with_an_expected_destination' logic in UpdateViewportsNewFrame() function)
19549
0
        IM_ASSERT(g.NextWindowData.Flags == 0);
19550
0
        if (g.IO.ConfigDockingWithShift && g.MouseStationaryTimer >= 1.0f && g.ActiveId >= 1.0f)
19551
0
            SetTooltip("%s", LocalizeGetMsg(ImGuiLocKey_DockingHoldShiftToDock));
19552
0
        return;
19553
0
    }
19554
19555
4.96k
    g.LastItemData.ID = window->MoveId;
19556
4.96k
    window = window->RootWindowDockTree;
19557
4.96k
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19558
4.96k
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
19559
4.96k
    ImGuiDragDropFlags drag_drop_flags = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_PayloadAutoExpire | ImGuiDragDropFlags_PayloadNoCrossContext | ImGuiDragDropFlags_PayloadNoCrossProcess;
19560
4.96k
    if (is_drag_docking && BeginDragDropSource(drag_drop_flags))
19561
3.48k
    {
19562
3.48k
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
19563
3.48k
        EndDragDropSource();
19564
3.48k
        StoreDockStyleForWindow(window); // Store style overrides while dragging (even when not docked) because docking preview may need it.
19565
3.48k
    }
19566
4.96k
}
19567
19568
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
19569
3.51k
{
19570
3.51k
    ImGuiContext& g = *GImGui;
19571
19572
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
19573
3.51k
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
19574
3.51k
    if (!g.DragDropActive)
19575
0
        return;
19576
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19577
3.51k
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
19578
3.50k
        return;
19579
19580
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
19581
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
19582
5
    const ImGuiPayload* payload = &g.DragDropPayload;
19583
5
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
19584
0
    {
19585
0
        EndDragDropTarget();
19586
0
        return;
19587
0
    }
19588
19589
5
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
19590
5
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
19591
5
    {
19592
        // Select target node
19593
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
19594
5
        bool dock_into_floating_window = false;
19595
5
        ImGuiDockNode* node = NULL;
19596
5
        if (window->DockNodeAsHost)
19597
0
        {
19598
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
19599
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
19600
19601
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
19602
            // In this case we need to fallback into any leaf mode, possibly the central node.
19603
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
19604
0
            if (node && node->IsDockSpace() && node->IsRootNode())
19605
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
19606
0
        }
19607
5
        else
19608
5
        {
19609
5
            if (window->DockNode)
19610
0
                node = window->DockNode;
19611
5
            else
19612
5
                dock_into_floating_window = true; // Dock into a regular window
19613
5
        }
19614
19615
5
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
19616
5
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
19617
19618
        // Preview docking request and find out split direction/ratio
19619
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
19620
5
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
19621
5
        if (do_preview && (node != NULL || dock_into_floating_window))
19622
0
        {
19623
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
19624
0
            ImGuiDockPreviewData split_inner;
19625
0
            ImGuiDockPreviewData split_outer;
19626
0
            ImGuiDockPreviewData* split_data = &split_inner;
19627
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
19628
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
19629
0
                {
19630
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
19631
0
                    if (split_outer.IsSplitDirExplicit)
19632
0
                        split_data = &split_outer;
19633
0
                }
19634
0
            if (!node || node->IsLeafNode())
19635
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
19636
0
            if (split_data == &split_outer)
19637
0
                split_inner.IsDropAllowed = false;
19638
19639
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
19640
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
19641
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
19642
19643
            // Queue docking request
19644
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
19645
0
                DockContextQueueDock(&g, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
19646
0
        }
19647
5
    }
19648
5
    EndDragDropTarget();
19649
5
}
19650
19651
//-----------------------------------------------------------------------------
19652
// Docking: Settings
19653
//-----------------------------------------------------------------------------
19654
// - DockSettingsRenameNodeReferences()
19655
// - DockSettingsRemoveNodeReferences()
19656
// - DockSettingsFindNodeSettings()
19657
// - DockSettingsHandler_ApplyAll()
19658
// - DockSettingsHandler_ReadOpen()
19659
// - DockSettingsHandler_ReadLine()
19660
// - DockSettingsHandler_DockNodeToSettings()
19661
// - DockSettingsHandler_WriteAll()
19662
//-----------------------------------------------------------------------------
19663
19664
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
19665
0
{
19666
0
    ImGuiContext& g = *GImGui;
19667
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
19668
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
19669
0
    {
19670
0
        ImGuiWindow* window = g.Windows[window_n];
19671
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
19672
0
            window->DockId = new_node_id;
19673
0
    }
19674
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19675
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19676
0
        if (settings->DockId == old_node_id)
19677
0
            settings->DockId = new_node_id;
19678
0
}
19679
19680
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
19681
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
19682
0
{
19683
0
    ImGuiContext& g = *GImGui;
19684
0
    int found = 0;
19685
    //// FIXME-OPT: We could remove this loop by storing the index in the map
19686
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19687
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
19688
0
            if (settings->DockId == node_ids[node_n])
19689
0
            {
19690
0
                settings->DockId = 0;
19691
0
                settings->DockOrder = -1;
19692
0
                if (++found < node_ids_count)
19693
0
                    break;
19694
0
                return;
19695
0
            }
19696
0
}
19697
19698
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
19699
0
{
19700
    // FIXME-OPT
19701
0
    ImGuiDockContext* dc = &ctx->DockContext;
19702
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
19703
0
        if (dc->NodesSettings[n].ID == id)
19704
0
            return &dc->NodesSettings[n];
19705
0
    return NULL;
19706
0
}
19707
19708
// Clear settings data
19709
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19710
0
{
19711
0
    ImGuiDockContext* dc = &ctx->DockContext;
19712
0
    dc->NodesSettings.clear();
19713
0
    DockContextClearNodes(ctx, 0, true);
19714
0
}
19715
19716
// Recreate nodes based on settings data
19717
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
19718
0
{
19719
    // Prune settings at boot time only
19720
0
    ImGuiDockContext* dc = &ctx->DockContext;
19721
0
    if (ctx->Windows.Size == 0)
19722
0
        DockContextPruneUnusedSettingsNodes(ctx);
19723
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
19724
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
19725
0
}
19726
19727
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
19728
0
{
19729
0
    if (strcmp(name, "Data") != 0)
19730
0
        return NULL;
19731
0
    return (void*)1;
19732
0
}
19733
19734
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
19735
0
{
19736
0
    char c = 0;
19737
0
    int x = 0, y = 0;
19738
0
    int r = 0;
19739
19740
    // Parsing, e.g.
19741
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
19742
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
19743
    // Important: this code expect currently fields in a fixed order.
19744
0
    ImGuiDockNodeSettings node;
19745
0
    line = ImStrSkipBlank(line);
19746
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
19747
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
19748
0
    else return;
19749
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
19750
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
19751
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
19752
0
    if (node.ParentNodeId == 0)
19753
0
    {
19754
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
19755
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
19756
0
    }
19757
0
    else
19758
0
    {
19759
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
19760
0
    }
19761
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
19762
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
19763
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
19764
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
19765
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
19766
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
19767
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
19768
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
19769
0
    if (node.ParentNodeId != 0)
19770
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
19771
0
            node.Depth = parent_settings->Depth + 1;
19772
0
    ctx->DockContext.NodesSettings.push_back(node);
19773
0
}
19774
19775
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
19776
0
{
19777
0
    ImGuiDockNodeSettings node_settings;
19778
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
19779
0
    node_settings.ID = node->ID;
19780
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
19781
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
19782
0
    node_settings.SelectedTabId = node->SelectedTabId;
19783
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
19784
0
    node_settings.Depth = (char)depth;
19785
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
19786
0
    node_settings.Pos = ImVec2ih(node->Pos);
19787
0
    node_settings.Size = ImVec2ih(node->Size);
19788
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
19789
0
    dc->NodesSettings.push_back(node_settings);
19790
0
    if (node->ChildNodes[0])
19791
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
19792
0
    if (node->ChildNodes[1])
19793
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
19794
0
}
19795
19796
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
19797
0
{
19798
0
    ImGuiContext& g = *ctx;
19799
0
    ImGuiDockContext* dc = &ctx->DockContext;
19800
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
19801
0
        return;
19802
19803
    // Gather settings data
19804
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
19805
0
    dc->NodesSettings.resize(0);
19806
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
19807
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
19808
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19809
0
            if (node->IsRootNode())
19810
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
19811
19812
0
    int max_depth = 0;
19813
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19814
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
19815
19816
    // Write to text buffer
19817
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
19818
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
19819
0
    {
19820
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
19821
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
19822
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
19823
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
19824
0
        if (node_settings->ParentNodeId)
19825
0
        {
19826
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
19827
0
        }
19828
0
        else
19829
0
        {
19830
0
            if (node_settings->ParentWindowId)
19831
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
19832
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
19833
0
        }
19834
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
19835
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
19836
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
19837
0
            buf->appendf(" NoResize=1");
19838
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
19839
0
            buf->appendf(" CentralNode=1");
19840
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
19841
0
            buf->appendf(" NoTabBar=1");
19842
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
19843
0
            buf->appendf(" HiddenTabBar=1");
19844
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
19845
0
            buf->appendf(" NoWindowMenuButton=1");
19846
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
19847
0
            buf->appendf(" NoCloseButton=1");
19848
0
        if (node_settings->SelectedTabId)
19849
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
19850
19851
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
19852
0
        if (g.IO.ConfigDebugIniSettings)
19853
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
19854
0
            {
19855
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
19856
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
19857
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
19858
                // Iterate settings so we can give info about windows that didn't exist during the session.
19859
0
                int contains_window = 0;
19860
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19861
0
                    if (settings->DockId == node_settings->ID)
19862
0
                    {
19863
0
                        if (contains_window++ == 0)
19864
0
                            buf->appendf(" ; contains ");
19865
0
                        buf->appendf("'%s' ", settings->GetName());
19866
0
                    }
19867
0
            }
19868
19869
0
        buf->appendf("\n");
19870
0
    }
19871
0
    buf->appendf("\n");
19872
0
}
19873
19874
19875
//-----------------------------------------------------------------------------
19876
// [SECTION] PLATFORM DEPENDENT HELPERS
19877
//-----------------------------------------------------------------------------
19878
// - Default clipboard handlers
19879
// - Default shell function handlers
19880
// - Default IME handlers
19881
//-----------------------------------------------------------------------------
19882
19883
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
19884
19885
#ifdef _MSC_VER
19886
#pragma comment(lib, "user32")
19887
#pragma comment(lib, "kernel32")
19888
#endif
19889
19890
// Win32 clipboard implementation
19891
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
19892
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19893
{
19894
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19895
    g.ClipboardHandlerData.clear();
19896
    if (!::OpenClipboard(NULL))
19897
        return NULL;
19898
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
19899
    if (wbuf_handle == NULL)
19900
    {
19901
        ::CloseClipboard();
19902
        return NULL;
19903
    }
19904
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
19905
    {
19906
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
19907
        g.ClipboardHandlerData.resize(buf_len);
19908
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
19909
    }
19910
    ::GlobalUnlock(wbuf_handle);
19911
    ::CloseClipboard();
19912
    return g.ClipboardHandlerData.Data;
19913
}
19914
19915
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19916
{
19917
    if (!::OpenClipboard(NULL))
19918
        return;
19919
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
19920
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
19921
    if (wbuf_handle == NULL)
19922
    {
19923
        ::CloseClipboard();
19924
        return;
19925
    }
19926
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
19927
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
19928
    ::GlobalUnlock(wbuf_handle);
19929
    ::EmptyClipboard();
19930
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
19931
        ::GlobalFree(wbuf_handle);
19932
    ::CloseClipboard();
19933
}
19934
19935
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
19936
19937
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
19938
static PasteboardRef main_clipboard = 0;
19939
19940
// OSX clipboard implementation
19941
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
19942
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
19943
{
19944
    if (!main_clipboard)
19945
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19946
    PasteboardClear(main_clipboard);
19947
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
19948
    if (cf_data)
19949
    {
19950
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
19951
        CFRelease(cf_data);
19952
    }
19953
}
19954
19955
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19956
{
19957
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19958
    if (!main_clipboard)
19959
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
19960
    PasteboardSynchronize(main_clipboard);
19961
19962
    ItemCount item_count = 0;
19963
    PasteboardGetItemCount(main_clipboard, &item_count);
19964
    for (ItemCount i = 0; i < item_count; i++)
19965
    {
19966
        PasteboardItemID item_id = 0;
19967
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
19968
        CFArrayRef flavor_type_array = 0;
19969
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
19970
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
19971
        {
19972
            CFDataRef cf_data;
19973
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
19974
            {
19975
                g.ClipboardHandlerData.clear();
19976
                int length = (int)CFDataGetLength(cf_data);
19977
                g.ClipboardHandlerData.resize(length + 1);
19978
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
19979
                g.ClipboardHandlerData[length] = 0;
19980
                CFRelease(cf_data);
19981
                return g.ClipboardHandlerData.Data;
19982
            }
19983
        }
19984
    }
19985
    return NULL;
19986
}
19987
19988
#else
19989
19990
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
19991
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
19992
0
{
19993
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
19994
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
19995
0
}
19996
19997
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
19998
0
{
19999
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
20000
0
    g.ClipboardHandlerData.clear();
20001
0
    const char* text_end = text + strlen(text);
20002
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
20003
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
20004
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
20005
0
}
20006
20007
#endif // Default clipboard handlers
20008
20009
//-----------------------------------------------------------------------------
20010
20011
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20012
#if defined(__APPLE__) && TARGET_OS_IPHONE
20013
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20014
#endif
20015
20016
#if defined(_WIN32) && defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
20017
#define IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20018
#endif
20019
#endif
20020
20021
#ifndef IMGUI_DISABLE_DEFAULT_SHELL_FUNCTIONS
20022
#ifdef _WIN32
20023
#include <shellapi.h>   // ShellExecuteA()
20024
#ifdef _MSC_VER
20025
#pragma comment(lib, "shell32")
20026
#endif
20027
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20028
{
20029
    return (INT_PTR)::ShellExecuteA(NULL, "open", path, NULL, NULL, SW_SHOWDEFAULT) > 32;
20030
}
20031
#else
20032
#include <sys/wait.h>
20033
#include <unistd.h>
20034
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char* path)
20035
0
{
20036
#if defined(__APPLE__)
20037
    const char* args[] { "open", "--", path, NULL };
20038
#else
20039
0
    const char* args[] { "xdg-open", path, NULL };
20040
0
#endif
20041
0
    pid_t pid = fork();
20042
0
    if (pid < 0)
20043
0
        return false;
20044
0
    if (!pid)
20045
0
    {
20046
0
        execvp(args[0], const_cast<char **>(args));
20047
0
        exit(-1);
20048
0
    }
20049
0
    else
20050
0
    {
20051
0
        int status;
20052
0
        waitpid(pid, &status, 0);
20053
0
        return WEXITSTATUS(status) == 0;
20054
0
    }
20055
0
}
20056
#endif
20057
#else
20058
static bool PlatformOpenInShellFn_DefaultImpl(ImGuiContext*, const char*) { return false; }
20059
#endif // Default shell handlers
20060
20061
//-----------------------------------------------------------------------------
20062
20063
// Win32 API IME support (for Asian languages, etc.)
20064
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
20065
20066
#include <imm.h>
20067
#ifdef _MSC_VER
20068
#pragma comment(lib, "imm32")
20069
#endif
20070
20071
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport* viewport, ImGuiPlatformImeData* data)
20072
{
20073
    // Notify OS Input Method Editor of text input position
20074
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
20075
    if (hwnd == 0)
20076
        return;
20077
20078
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
20079
    if (HIMC himc = ::ImmGetContext(hwnd))
20080
    {
20081
        COMPOSITIONFORM composition_form = {};
20082
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20083
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20084
        composition_form.dwStyle = CFS_FORCE_POSITION;
20085
        ::ImmSetCompositionWindow(himc, &composition_form);
20086
        CANDIDATEFORM candidate_form = {};
20087
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
20088
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
20089
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
20090
        ::ImmSetCandidateWindow(himc, &candidate_form);
20091
        ::ImmReleaseContext(hwnd, himc);
20092
    }
20093
}
20094
20095
#else
20096
20097
0
static void PlatformSetImeDataFn_DefaultImpl(ImGuiContext*, ImGuiViewport*, ImGuiPlatformImeData*) {}
20098
20099
#endif // Default IME handlers
20100
20101
//-----------------------------------------------------------------------------
20102
// [SECTION] METRICS/DEBUGGER WINDOW
20103
//-----------------------------------------------------------------------------
20104
// - DebugRenderViewportThumbnail() [Internal]
20105
// - RenderViewportsThumbnails() [Internal]
20106
// - DebugTextEncoding()
20107
// - MetricsHelpMarker() [Internal]
20108
// - ShowFontAtlas() [Internal]
20109
// - ShowMetricsWindow()
20110
// - DebugNodeColumns() [Internal]
20111
// - DebugNodeDockNode() [Internal]
20112
// - DebugNodeDrawList() [Internal]
20113
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
20114
// - DebugNodeFont() [Internal]
20115
// - DebugNodeFontGlyph() [Internal]
20116
// - DebugNodeStorage() [Internal]
20117
// - DebugNodeTabBar() [Internal]
20118
// - DebugNodeViewport() [Internal]
20119
// - DebugNodeWindow() [Internal]
20120
// - DebugNodeWindowSettings() [Internal]
20121
// - DebugNodeWindowsList() [Internal]
20122
// - DebugNodeWindowsListByBeginStackParent() [Internal]
20123
//-----------------------------------------------------------------------------
20124
20125
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
20126
20127
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
20128
0
{
20129
0
    ImGuiContext& g = *GImGui;
20130
0
    ImGuiWindow* window = g.CurrentWindow;
20131
20132
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
20133
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
20134
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
20135
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
20136
0
    for (ImGuiWindow* thumb_window : g.Windows)
20137
0
    {
20138
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
20139
0
            continue;
20140
0
        if (thumb_window->Viewport != viewport)
20141
0
            continue;
20142
20143
0
        ImRect thumb_r = thumb_window->Rect();
20144
0
        ImRect title_r = thumb_window->TitleBarRect();
20145
0
        thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off +  thumb_r.Max * scale));
20146
0
        title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off +  ImVec2(title_r.Max.x, title_r.Min.y + title_r.GetHeight() * 3.0f) * scale)); // Exaggerate title bar height
20147
0
        thumb_r.ClipWithFull(bb);
20148
0
        title_r.ClipWithFull(bb);
20149
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
20150
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
20151
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
20152
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20153
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
20154
0
    }
20155
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
20156
0
    if (viewport->ID == g.DebugMetricsConfig.HighlightViewportID)
20157
0
        window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
20158
0
}
20159
20160
static void RenderViewportsThumbnails()
20161
0
{
20162
0
    ImGuiContext& g = *GImGui;
20163
0
    ImGuiWindow* window = g.CurrentWindow;
20164
20165
    // Draw monitor and calculate their boundaries
20166
0
    float SCALE = 1.0f / 8.0f;
20167
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20168
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20169
0
        bb_full.Add(ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize));
20170
0
    ImVec2 p = window->DC.CursorPos;
20171
0
    ImVec2 off = p - bb_full.Min * SCALE;
20172
0
    for (ImGuiPlatformMonitor& monitor : g.PlatformIO.Monitors)
20173
0
    {
20174
0
        ImRect monitor_draw_bb(off + (monitor.MainPos) * SCALE, off + (monitor.MainPos + monitor.MainSize) * SCALE);
20175
0
        window->DrawList->AddRect(monitor_draw_bb.Min, monitor_draw_bb.Max, (g.DebugMetricsConfig.HighlightMonitorIdx == g.PlatformIO.Monitors.index_from_ptr(&monitor)) ? IM_COL32(255, 255, 0, 255) : ImGui::GetColorU32(ImGuiCol_Border), 4.0f);
20176
0
        window->DrawList->AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui::GetColorU32(ImGuiCol_Border, 0.10f), 4.0f);
20177
0
    }
20178
20179
    // Draw viewports
20180
0
    for (ImGuiViewportP* viewport : g.Viewports)
20181
0
    {
20182
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
20183
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
20184
0
    }
20185
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
20186
0
}
20187
20188
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
20189
0
{
20190
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
20191
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
20192
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
20193
0
}
20194
20195
// Draw an arbitrary US keyboard layout to visualize translated keys
20196
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
20197
0
{
20198
0
    const float scale = ImGui::GetFontSize() / 13.0f;
20199
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f) * scale;
20200
0
    const float  key_rounding = 3.0f * scale;
20201
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f) * scale;
20202
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f) * scale;
20203
0
    const float  key_face_rounding = 2.0f * scale;
20204
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f) * scale;
20205
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
20206
0
    const float  key_row_offset = 9.0f * scale;
20207
20208
0
    ImVec2 board_min = GetCursorScreenPos();
20209
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
20210
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
20211
20212
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
20213
0
    const KeyLayoutData keys_to_display[] =
20214
0
    {
20215
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
20216
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
20217
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
20218
0
    };
20219
20220
    // Elements rendered manually via ImDrawList API are not clipped automatically.
20221
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
20222
0
    Dummy(board_max - board_min);
20223
0
    if (!IsItemVisible())
20224
0
        return;
20225
0
    draw_list->PushClipRect(board_min, board_max, true);
20226
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
20227
0
    {
20228
0
        const KeyLayoutData* key_data = &keys_to_display[n];
20229
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
20230
0
        ImVec2 key_max = key_min + key_size;
20231
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
20232
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
20233
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
20234
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
20235
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
20236
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
20237
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
20238
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
20239
0
        if (IsKeyDown(key_data->Key))
20240
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
20241
0
    }
20242
0
    draw_list->PopClipRect();
20243
0
}
20244
20245
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
20246
void ImGui::DebugTextEncoding(const char* str)
20247
0
{
20248
0
    Text("Text: \"%s\"", str);
20249
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
20250
0
        return;
20251
0
    TableSetupColumn("Offset");
20252
0
    TableSetupColumn("UTF-8");
20253
0
    TableSetupColumn("Glyph");
20254
0
    TableSetupColumn("Codepoint");
20255
0
    TableHeadersRow();
20256
0
    for (const char* p = str; *p != 0; )
20257
0
    {
20258
0
        unsigned int c;
20259
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
20260
0
        TableNextColumn();
20261
0
        Text("%d", (int)(p - str));
20262
0
        TableNextColumn();
20263
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
20264
0
        {
20265
0
            if (byte_index > 0)
20266
0
                SameLine();
20267
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
20268
0
        }
20269
0
        TableNextColumn();
20270
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
20271
0
            TextUnformatted(p, p + c_utf8_len);
20272
0
        else
20273
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
20274
0
        TableNextColumn();
20275
0
        Text("U+%04X", (int)c);
20276
0
        p += c_utf8_len;
20277
0
    }
20278
0
    EndTable();
20279
0
}
20280
20281
static void DebugFlashStyleColorStop()
20282
0
{
20283
0
    ImGuiContext& g = *GImGui;
20284
0
    if (g.DebugFlashStyleColorIdx != ImGuiCol_COUNT)
20285
0
        g.Style.Colors[g.DebugFlashStyleColorIdx] = g.DebugFlashStyleColorBackup;
20286
0
    g.DebugFlashStyleColorIdx = ImGuiCol_COUNT;
20287
0
}
20288
20289
// Flash a given style color for some + inhibit modifications of this color via PushStyleColor() calls.
20290
void ImGui::DebugFlashStyleColor(ImGuiCol idx)
20291
0
{
20292
0
    ImGuiContext& g = *GImGui;
20293
0
    DebugFlashStyleColorStop();
20294
0
    g.DebugFlashStyleColorTime = 0.5f;
20295
0
    g.DebugFlashStyleColorIdx = idx;
20296
0
    g.DebugFlashStyleColorBackup = g.Style.Colors[idx];
20297
0
}
20298
20299
void ImGui::UpdateDebugToolFlashStyleColor()
20300
80.5k
{
20301
80.5k
    ImGuiContext& g = *GImGui;
20302
80.5k
    if (g.DebugFlashStyleColorTime <= 0.0f)
20303
80.5k
        return;
20304
0
    ColorConvertHSVtoRGB(cosf(g.DebugFlashStyleColorTime * 6.0f) * 0.5f + 0.5f, 0.5f, 0.5f, g.Style.Colors[g.DebugFlashStyleColorIdx].x, g.Style.Colors[g.DebugFlashStyleColorIdx].y, g.Style.Colors[g.DebugFlashStyleColorIdx].z);
20305
0
    g.Style.Colors[g.DebugFlashStyleColorIdx].w = 1.0f;
20306
0
    if ((g.DebugFlashStyleColorTime -= g.IO.DeltaTime) <= 0.0f)
20307
0
        DebugFlashStyleColorStop();
20308
0
}
20309
20310
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
20311
static void MetricsHelpMarker(const char* desc)
20312
0
{
20313
0
    ImGui::TextDisabled("(?)");
20314
0
    if (ImGui::BeginItemTooltip())
20315
0
    {
20316
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
20317
0
        ImGui::TextUnformatted(desc);
20318
0
        ImGui::PopTextWrapPos();
20319
0
        ImGui::EndTooltip();
20320
0
    }
20321
0
}
20322
20323
// [DEBUG] List fonts in a font atlas and display its texture
20324
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
20325
0
{
20326
0
    for (ImFont* font : atlas->Fonts)
20327
0
    {
20328
0
        PushID(font);
20329
0
        DebugNodeFont(font);
20330
0
        PopID();
20331
0
    }
20332
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
20333
0
    {
20334
0
        ImGuiContext& g = *GImGui;
20335
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20336
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
20337
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
20338
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
20339
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
20340
0
        TreePop();
20341
0
    }
20342
0
}
20343
20344
void ImGui::ShowMetricsWindow(bool* p_open)
20345
0
{
20346
0
    ImGuiContext& g = *GImGui;
20347
0
    ImGuiIO& io = g.IO;
20348
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
20349
0
    if (cfg->ShowDebugLog)
20350
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
20351
0
    if (cfg->ShowIDStackTool)
20352
0
        ShowIDStackToolWindow(&cfg->ShowIDStackTool);
20353
20354
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
20355
0
    {
20356
0
        End();
20357
0
        return;
20358
0
    }
20359
20360
    // [DEBUG] Clear debug breaks hooks after exactly one cycle.
20361
0
    DebugBreakClearData();
20362
20363
    // Basic info
20364
0
    Text("Dear ImGui %s", GetVersion());
20365
0
    if (g.ContextName[0] != 0)
20366
0
    {
20367
0
        SameLine();
20368
0
        Text("(Context Name: \"%s\")", g.ContextName);
20369
0
    }
20370
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
20371
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
20372
0
    Text("%d visible windows, %d current allocations", io.MetricsRenderWindows, g.DebugAllocInfo.TotalAllocCount - g.DebugAllocInfo.TotalFreeCount);
20373
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
20374
20375
0
    Separator();
20376
20377
    // Debugging enums
20378
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
20379
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
20380
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
20381
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
20382
0
    if (cfg->ShowWindowsRectsType < 0)
20383
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
20384
0
    if (cfg->ShowTablesRectsType < 0)
20385
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
20386
20387
0
    struct Funcs
20388
0
    {
20389
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
20390
0
        {
20391
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
20392
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
20393
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
20394
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
20395
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
20396
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
20397
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
20398
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
20399
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
20400
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
20401
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); } // Note: y1/y2 not always accurate
20402
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastTopHeadersRowHeight); }
20403
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
20404
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
20405
0
            IM_ASSERT(0);
20406
0
            return ImRect();
20407
0
        }
20408
20409
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
20410
0
        {
20411
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
20412
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
20413
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
20414
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
20415
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
20416
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
20417
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
20418
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
20419
0
            IM_ASSERT(0);
20420
0
            return ImRect();
20421
0
        }
20422
0
    };
20423
20424
    // Tools
20425
0
    if (TreeNode("Tools"))
20426
0
    {
20427
        // Debug Break features
20428
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
20429
0
        SeparatorTextEx(0, "Debug breaks", NULL, CalcTextSize("(?)").x + g.Style.SeparatorTextPadding.x);
20430
0
        SameLine();
20431
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
20432
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
20433
0
            DebugStartItemPicker();
20434
0
        Checkbox("Show \"Debug Break\" buttons in other sections (io.ConfigDebugIsDebuggerPresent)", &g.IO.ConfigDebugIsDebuggerPresent);
20435
20436
0
        SeparatorText("Visualize");
20437
20438
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
20439
0
        SameLine();
20440
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
20441
20442
0
        Checkbox("Show ID Stack Tool", &cfg->ShowIDStackTool);
20443
0
        SameLine();
20444
0
        MetricsHelpMarker("You can also call ImGui::ShowIDStackToolWindow() from your code.");
20445
20446
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
20447
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
20448
0
        SameLine();
20449
0
        SetNextItemWidth(GetFontSize() * 12);
20450
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
20451
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
20452
0
        {
20453
0
            BulletText("'%s':", g.NavWindow->Name);
20454
0
            Indent();
20455
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
20456
0
            {
20457
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
20458
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
20459
0
            }
20460
0
            Unindent();
20461
0
        }
20462
20463
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
20464
0
        SameLine();
20465
0
        SetNextItemWidth(GetFontSize() * 12);
20466
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
20467
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
20468
0
        {
20469
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20470
0
            {
20471
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20472
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
20473
0
                    continue;
20474
20475
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
20476
0
                if (IsItemHovered())
20477
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20478
0
                Indent();
20479
0
                char buf[128];
20480
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
20481
0
                {
20482
0
                    if (rect_n >= TRT_ColumnsRect)
20483
0
                    {
20484
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
20485
0
                            continue;
20486
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20487
0
                        {
20488
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
20489
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
20490
0
                            Selectable(buf);
20491
0
                            if (IsItemHovered())
20492
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20493
0
                        }
20494
0
                    }
20495
0
                    else
20496
0
                    {
20497
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
20498
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
20499
0
                        Selectable(buf);
20500
0
                        if (IsItemHovered())
20501
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
20502
0
                    }
20503
0
                }
20504
0
                Unindent();
20505
0
            }
20506
0
        }
20507
0
        Checkbox("Show groups rectangles", &g.DebugShowGroupRects); // Storing in context as this is used by group code and prefers to be in hot-data
20508
20509
0
        SeparatorText("Validate");
20510
20511
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
20512
0
        SameLine();
20513
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
20514
20515
0
        Checkbox("UTF-8 Encoding viewer", &cfg->ShowTextEncodingViewer);
20516
0
        SameLine();
20517
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
20518
0
        if (cfg->ShowTextEncodingViewer)
20519
0
        {
20520
0
            static char buf[64] = "";
20521
0
            SetNextItemWidth(-FLT_MIN);
20522
0
            InputText("##DebugTextEncodingBuf", buf, IM_ARRAYSIZE(buf));
20523
0
            if (buf[0] != 0)
20524
0
                DebugTextEncoding(buf);
20525
0
        }
20526
20527
0
        TreePop();
20528
0
    }
20529
20530
    // Windows
20531
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
20532
0
    {
20533
        //SetNextItemOpen(true, ImGuiCond_Once);
20534
0
        DebugNodeWindowsList(&g.Windows, "By display order");
20535
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
20536
0
        if (TreeNode("By submission order (begin stack)"))
20537
0
        {
20538
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
20539
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
20540
0
            temp_buffer.resize(0);
20541
0
            for (ImGuiWindow* window : g.Windows)
20542
0
                if (window->LastFrameActive + 1 >= g.FrameCount)
20543
0
                    temp_buffer.push_back(window);
20544
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
20545
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
20546
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
20547
0
            TreePop();
20548
0
        }
20549
20550
0
        TreePop();
20551
0
    }
20552
20553
    // DrawLists
20554
0
    int drawlist_count = 0;
20555
0
    for (ImGuiViewportP* viewport : g.Viewports)
20556
0
        drawlist_count += viewport->DrawDataP.CmdLists.Size;
20557
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
20558
0
    {
20559
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
20560
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
20561
0
        for (ImGuiViewportP* viewport : g.Viewports)
20562
0
        {
20563
0
            bool viewport_has_drawlist = false;
20564
0
            for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
20565
0
            {
20566
0
                if (!viewport_has_drawlist)
20567
0
                    Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
20568
0
                viewport_has_drawlist = true;
20569
0
                DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
20570
0
            }
20571
0
        }
20572
0
        TreePop();
20573
0
    }
20574
20575
    // Viewports
20576
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
20577
0
    {
20578
0
        cfg->HighlightMonitorIdx = -1;
20579
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
20580
0
        SameLine();
20581
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
20582
0
        if (open)
20583
0
        {
20584
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
20585
0
            {
20586
0
                DebugNodePlatformMonitor(&g.PlatformIO.Monitors[i], "Monitor", i);
20587
0
                if (IsItemHovered())
20588
0
                    cfg->HighlightMonitorIdx = i;
20589
0
            }
20590
0
            DebugNodePlatformMonitor(&g.FallbackMonitor, "Fallback", 0);
20591
0
            TreePop();
20592
0
        }
20593
20594
0
        SetNextItemOpen(true, ImGuiCond_Once);
20595
0
        if (TreeNode("Windows Minimap"))
20596
0
        {
20597
0
            RenderViewportsThumbnails();
20598
0
            TreePop();
20599
0
        }
20600
0
        cfg->HighlightViewportID = 0;
20601
20602
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20603
0
        if (TreeNode("Inferred Z order (front-to-back)"))
20604
0
        {
20605
0
            static ImVector<ImGuiViewportP*> viewports;
20606
0
            viewports.resize(g.Viewports.Size);
20607
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
20608
0
            if (viewports.Size > 1)
20609
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
20610
0
            for (ImGuiViewportP* viewport : viewports)
20611
0
            {
20612
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
20613
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
20614
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
20615
0
                    viewport->Window ? viewport->Window->Name : "N/A");
20616
0
                if (IsItemHovered())
20617
0
                    cfg->HighlightViewportID = viewport->ID;
20618
0
            }
20619
0
            TreePop();
20620
0
        }
20621
20622
0
        for (ImGuiViewportP* viewport : g.Viewports)
20623
0
            DebugNodeViewport(viewport);
20624
0
        TreePop();
20625
0
    }
20626
20627
    // Details for Popups
20628
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
20629
0
    {
20630
0
        for (const ImGuiPopupData& popup_data : g.OpenPopupStack)
20631
0
        {
20632
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
20633
0
            ImGuiWindow* window = popup_data.Window;
20634
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'",
20635
0
                popup_data.PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
20636
0
                popup_data.RestoreNavWindow ? popup_data.RestoreNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
20637
0
        }
20638
0
        TreePop();
20639
0
    }
20640
20641
    // Details for TabBars
20642
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
20643
0
    {
20644
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
20645
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
20646
0
            {
20647
0
                PushID(tab_bar);
20648
0
                DebugNodeTabBar(tab_bar, "TabBar");
20649
0
                PopID();
20650
0
            }
20651
0
        TreePop();
20652
0
    }
20653
20654
    // Details for Tables
20655
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
20656
0
    {
20657
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
20658
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
20659
0
                DebugNodeTable(table);
20660
0
        TreePop();
20661
0
    }
20662
20663
    // Details for Fonts
20664
0
    ImFontAtlas* atlas = g.IO.Fonts;
20665
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
20666
0
    {
20667
0
        ShowFontAtlas(atlas);
20668
0
        TreePop();
20669
0
    }
20670
20671
    // Details for InputText
20672
0
    if (TreeNode("InputText"))
20673
0
    {
20674
0
        DebugNodeInputTextState(&g.InputTextState);
20675
0
        TreePop();
20676
0
    }
20677
20678
    // Details for TypingSelect
20679
0
    if (TreeNode("TypingSelect", "TypingSelect (%d)", g.TypingSelectState.SearchBuffer[0] != 0 ? 1 : 0))
20680
0
    {
20681
0
        DebugNodeTypingSelectState(&g.TypingSelectState);
20682
0
        TreePop();
20683
0
    }
20684
20685
    // Details for MultiSelect
20686
0
    if (TreeNode("MultiSelect", "MultiSelect (%d)", g.MultiSelectStorage.GetAliveCount()))
20687
0
    {
20688
0
        ImGuiBoxSelectState* bs = &g.BoxSelectState;
20689
0
        BulletText("BoxSelect ID=0x%08X, Starting = %d, Active %d", bs->ID, bs->IsStarting, bs->IsActive);
20690
0
        for (int n = 0; n < g.MultiSelectStorage.GetMapSize(); n++)
20691
0
            if (ImGuiMultiSelectState* state = g.MultiSelectStorage.TryGetMapData(n))
20692
0
                DebugNodeMultiSelectState(state);
20693
0
        TreePop();
20694
0
    }
20695
20696
    // Details for Docking
20697
0
#ifdef IMGUI_HAS_DOCK
20698
0
    if (TreeNode("Docking"))
20699
0
    {
20700
0
        static bool root_nodes_only = true;
20701
0
        ImGuiDockContext* dc = &g.DockContext;
20702
0
        Checkbox("List root nodes", &root_nodes_only);
20703
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
20704
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
20705
0
        SameLine();
20706
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
20707
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
20708
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
20709
0
                if (!root_nodes_only || node->IsRootNode())
20710
0
                    DebugNodeDockNode(node, "Node");
20711
0
        TreePop();
20712
0
    }
20713
0
#endif // #ifdef IMGUI_HAS_DOCK
20714
20715
    // Settings
20716
0
    if (TreeNode("Settings"))
20717
0
    {
20718
0
        if (SmallButton("Clear"))
20719
0
            ClearIniSettings();
20720
0
        SameLine();
20721
0
        if (SmallButton("Save to memory"))
20722
0
            SaveIniSettingsToMemory();
20723
0
        SameLine();
20724
0
        if (SmallButton("Save to disk"))
20725
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
20726
0
        SameLine();
20727
0
        if (g.IO.IniFilename)
20728
0
            Text("\"%s\"", g.IO.IniFilename);
20729
0
        else
20730
0
            TextUnformatted("<NULL>");
20731
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
20732
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
20733
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
20734
0
        {
20735
0
            for (ImGuiSettingsHandler& handler : g.SettingsHandlers)
20736
0
                BulletText("\"%s\"", handler.TypeName);
20737
0
            TreePop();
20738
0
        }
20739
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
20740
0
        {
20741
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20742
0
                DebugNodeWindowSettings(settings);
20743
0
            TreePop();
20744
0
        }
20745
20746
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
20747
0
        {
20748
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
20749
0
                DebugNodeTableSettings(settings);
20750
0
            TreePop();
20751
0
        }
20752
20753
0
#ifdef IMGUI_HAS_DOCK
20754
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
20755
0
        {
20756
0
            ImGuiDockContext* dc = &g.DockContext;
20757
0
            Text("In SettingsWindows:");
20758
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
20759
0
                if (settings->DockId != 0)
20760
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
20761
0
            Text("In SettingsNodes:");
20762
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
20763
0
            {
20764
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
20765
0
                const char* selected_tab_name = NULL;
20766
0
                if (settings->SelectedTabId)
20767
0
                {
20768
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
20769
0
                        selected_tab_name = window->Name;
20770
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
20771
0
                        selected_tab_name = window_settings->GetName();
20772
0
                }
20773
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
20774
0
            }
20775
0
            TreePop();
20776
0
        }
20777
0
#endif // #ifdef IMGUI_HAS_DOCK
20778
20779
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
20780
0
        {
20781
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
20782
0
            TreePop();
20783
0
        }
20784
0
        TreePop();
20785
0
    }
20786
20787
    // Settings
20788
0
    if (TreeNode("Memory allocations"))
20789
0
    {
20790
0
        ImGuiDebugAllocInfo* info = &g.DebugAllocInfo;
20791
0
        Text("%d current allocations", info->TotalAllocCount - info->TotalFreeCount);
20792
0
        if (SmallButton("GC now")) { g.GcCompactAll = true; }
20793
0
        Text("Recent frames with allocations:");
20794
0
        int buf_size = IM_ARRAYSIZE(info->LastEntriesBuf);
20795
0
        for (int n = buf_size - 1; n >= 0; n--)
20796
0
        {
20797
0
            ImGuiDebugAllocEntry* entry = &info->LastEntriesBuf[(info->LastEntriesIdx - n + buf_size) % buf_size];
20798
0
            BulletText("Frame %06d: %+3d ( %2d malloc, %2d free )%s", entry->FrameCount, entry->AllocCount - entry->FreeCount, entry->AllocCount, entry->FreeCount, (n == 0) ? " (most recent)" : "");
20799
0
        }
20800
0
        TreePop();
20801
0
    }
20802
20803
0
    if (TreeNode("Inputs"))
20804
0
    {
20805
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
20806
0
        {
20807
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
20808
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
20809
0
            Indent();
20810
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
20811
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
20812
#else
20813
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key >= 0 && key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
20814
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
20815
#endif
20816
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
20817
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20818
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
20819
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
20820
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
20821
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
20822
0
            Unindent();
20823
0
        }
20824
20825
0
        Text("MOUSE STATE");
20826
0
        {
20827
0
            Indent();
20828
0
            if (IsMousePosValid())
20829
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
20830
0
            else
20831
0
                Text("Mouse pos: <INVALID>");
20832
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
20833
0
            int count = IM_ARRAYSIZE(io.MouseDown);
20834
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
20835
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
20836
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
20837
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
20838
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
20839
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
20840
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
20841
0
            Unindent();
20842
0
        }
20843
20844
0
        Text("MOUSE WHEELING");
20845
0
        {
20846
0
            Indent();
20847
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
20848
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
20849
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
20850
0
            Unindent();
20851
0
        }
20852
20853
0
        Text("KEY OWNERS");
20854
0
        {
20855
0
            Indent();
20856
0
            if (BeginChild("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20857
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20858
0
                {
20859
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
20860
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_NoOwner)
20861
0
                        continue;
20862
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
20863
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
20864
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
20865
0
                }
20866
0
            EndChild();
20867
0
            Unindent();
20868
0
        }
20869
0
        Text("SHORTCUT ROUTING");
20870
0
        SameLine();
20871
0
        MetricsHelpMarker("Declared shortcut routes automatically set key owner when mods matches.");
20872
0
        {
20873
0
            Indent();
20874
0
            if (BeginChild("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 8), ImGuiChildFlags_FrameStyle | ImGuiChildFlags_ResizeY, ImGuiWindowFlags_NoSavedSettings))
20875
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
20876
0
                {
20877
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
20878
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
20879
0
                    {
20880
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
20881
0
                        ImGuiKeyChord key_chord = key | routing_data->Mods;
20882
0
                        Text("%s: 0x%08X (scored %d)", GetKeyChordName(key_chord), routing_data->RoutingCurr, routing_data->RoutingCurrScore);
20883
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
20884
0
                        if (g.IO.ConfigDebugIsDebuggerPresent)
20885
0
                        {
20886
0
                            SameLine();
20887
0
                            if (DebugBreakButton("**DebugBreak**", "in SetShortcutRouting() for this KeyChord"))
20888
0
                                g.DebugBreakInShortcutRouting = key_chord;
20889
0
                        }
20890
0
                        idx = routing_data->NextEntryIndex;
20891
0
                    }
20892
0
                }
20893
0
            EndChild();
20894
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20895
0
            Unindent();
20896
0
        }
20897
0
        TreePop();
20898
0
    }
20899
20900
0
    if (TreeNode("Internal state"))
20901
0
    {
20902
0
        Text("WINDOWING");
20903
0
        Indent();
20904
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
20905
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
20906
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
20907
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
20908
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
20909
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
20910
0
        Unindent();
20911
20912
0
        Text("ITEMS");
20913
0
        Indent();
20914
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
20915
0
        DebugLocateItemOnHover(g.ActiveId);
20916
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
20917
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
20918
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
20919
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
20920
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
20921
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
20922
0
        Unindent();
20923
20924
0
        Text("NAV,FOCUS");
20925
0
        Indent();
20926
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
20927
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
20928
0
        DebugLocateItemOnHover(g.NavId);
20929
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
20930
0
        Text("NavLastValidSelectionUserData = %" IM_PRId64 " (0x%" IM_PRIX64 ")", g.NavLastValidSelectionUserData, g.NavLastValidSelectionUserData);
20931
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
20932
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
20933
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
20934
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
20935
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
20936
0
        Text("NavFocusRoute[] = ");
20937
0
        for (int path_n = g.NavFocusRoute.Size - 1; path_n >= 0; path_n--)
20938
0
        {
20939
0
            const ImGuiFocusScopeData& focus_scope = g.NavFocusRoute[path_n];
20940
0
            SameLine(0.0f, 0.0f);
20941
0
            Text("0x%08X/", focus_scope.ID);
20942
0
            SetItemTooltip("In window \"%s\"", FindWindowByID(focus_scope.WindowID)->Name);
20943
0
        }
20944
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
20945
0
        Unindent();
20946
20947
0
        TreePop();
20948
0
    }
20949
20950
    // Overlay: Display windows Rectangles and Begin Order
20951
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
20952
0
    {
20953
0
        for (ImGuiWindow* window : g.Windows)
20954
0
        {
20955
0
            if (!window->WasActive)
20956
0
                continue;
20957
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
20958
0
            if (cfg->ShowWindowsRects)
20959
0
            {
20960
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
20961
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20962
0
            }
20963
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
20964
0
            {
20965
0
                char buf[32];
20966
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
20967
0
                float font_size = GetFontSize();
20968
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
20969
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
20970
0
            }
20971
0
        }
20972
0
    }
20973
20974
    // Overlay: Display Tables Rectangles
20975
0
    if (cfg->ShowTablesRects)
20976
0
    {
20977
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
20978
0
        {
20979
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
20980
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
20981
0
                continue;
20982
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
20983
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
20984
0
            {
20985
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
20986
0
                {
20987
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
20988
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
20989
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
20990
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
20991
0
                }
20992
0
            }
20993
0
            else
20994
0
            {
20995
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
20996
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
20997
0
            }
20998
0
        }
20999
0
    }
21000
21001
0
#ifdef IMGUI_HAS_DOCK
21002
    // Overlay: Display Docking info
21003
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
21004
0
    {
21005
0
        char buf[64] = "";
21006
0
        char* p = buf;
21007
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
21008
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
21009
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
21010
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
21011
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
21012
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
21013
0
        int depth = DockNodeGetDepth(node);
21014
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
21015
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
21016
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
21017
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
21018
0
    }
21019
0
#endif // #ifdef IMGUI_HAS_DOCK
21020
21021
0
    End();
21022
0
}
21023
21024
void ImGui::DebugBreakClearData()
21025
0
{
21026
    // Those fields are scattered in their respective subsystem to stay in hot-data locations
21027
0
    ImGuiContext& g = *GImGui;
21028
0
    g.DebugBreakInWindow = 0;
21029
0
    g.DebugBreakInTable = 0;
21030
0
    g.DebugBreakInShortcutRouting = ImGuiKey_None;
21031
0
}
21032
21033
void ImGui::DebugBreakButtonTooltip(bool keyboard_only, const char* description_of_location)
21034
0
{
21035
0
    if (!BeginItemTooltip())
21036
0
        return;
21037
0
    Text("To call IM_DEBUG_BREAK() %s:", description_of_location);
21038
0
    Separator();
21039
0
    TextUnformatted(keyboard_only ? "- Press 'Pause/Break' on keyboard." : "- Press 'Pause/Break' on keyboard.\n- or Click (may alter focus/active id).\n- or navigate using keyboard and press space.");
21040
0
    Separator();
21041
0
    TextUnformatted("Choose one way that doesn't interfere with what you are trying to debug!\nYou need a debugger attached or this will crash!");
21042
0
    EndTooltip();
21043
0
}
21044
21045
// Special button that doesn't take focus, doesn't take input owner, and can be activated without a click etc.
21046
// In order to reduce interferences with the contents we are trying to debug into.
21047
bool ImGui::DebugBreakButton(const char* label, const char* description_of_location)
21048
0
{
21049
0
    ImGuiWindow* window = GetCurrentWindow();
21050
0
    if (window->SkipItems)
21051
0
        return false;
21052
21053
0
    ImGuiContext& g = *GImGui;
21054
0
    const ImGuiID id = window->GetID(label);
21055
0
    const ImVec2 label_size = CalcTextSize(label, NULL, true);
21056
0
    ImVec2 pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrLineTextBaseOffset);
21057
0
    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x * 2.0f, label_size.y);
21058
21059
0
    const ImRect bb(pos, pos + size);
21060
0
    ItemSize(size, 0.0f);
21061
0
    if (!ItemAdd(bb, id))
21062
0
        return false;
21063
21064
    // WE DO NOT USE ButtonEx() or ButtonBehavior() in order to reduce our side-effects.
21065
0
    bool hovered = ItemHoverable(bb, id, g.CurrentItemFlags);
21066
0
    bool pressed = hovered && (IsKeyChordPressed(g.DebugBreakKeyChord) || IsMouseClicked(0) || g.NavActivateId == id);
21067
0
    DebugBreakButtonTooltip(false, description_of_location);
21068
21069
0
    ImVec4 col4f = GetStyleColorVec4(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
21070
0
    ImVec4 hsv;
21071
0
    ColorConvertRGBtoHSV(col4f.x, col4f.y, col4f.z, hsv.x, hsv.y, hsv.z);
21072
0
    ColorConvertHSVtoRGB(hsv.x + 0.20f, hsv.y, hsv.z, col4f.x, col4f.y, col4f.z);
21073
21074
0
    RenderNavHighlight(bb, id);
21075
0
    RenderFrame(bb.Min, bb.Max, GetColorU32(col4f), true, g.Style.FrameRounding);
21076
0
    RenderTextClipped(bb.Min, bb.Max, label, NULL, &label_size, g.Style.ButtonTextAlign, &bb);
21077
21078
0
    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
21079
0
    return pressed;
21080
0
}
21081
21082
// [DEBUG] Display contents of Columns
21083
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
21084
0
{
21085
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
21086
0
        return;
21087
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
21088
0
    for (ImGuiOldColumnData& column : columns->Columns)
21089
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", (int)columns->Columns.index_from_ptr(&column), column.OffsetNorm, GetColumnOffsetFromNorm(columns, column.OffsetNorm));
21090
0
    TreePop();
21091
0
}
21092
21093
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
21094
0
{
21095
0
    using namespace ImGui;
21096
0
    PushID(label);
21097
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
21098
0
    Text("%s:", label);
21099
0
    if (!enabled)
21100
0
        BeginDisabled();
21101
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
21102
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
21103
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
21104
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
21105
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
21106
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
21107
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
21108
0
    CheckboxFlags("DockedWindowsInFocusRoute", p_flags, ImGuiDockNodeFlags_DockedWindowsInFocusRoute);
21109
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking); // Multiple flags
21110
0
    CheckboxFlags("NoDockingSplit", p_flags, ImGuiDockNodeFlags_NoDockingSplit);
21111
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
21112
0
    CheckboxFlags("NoDockingOver", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
21113
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
21114
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
21115
0
    CheckboxFlags("NoUndocking", p_flags, ImGuiDockNodeFlags_NoUndocking);
21116
0
    if (!enabled)
21117
0
        EndDisabled();
21118
0
    PopStyleVar();
21119
0
    PopID();
21120
0
}
21121
21122
// [DEBUG] Display contents of ImDockNode
21123
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
21124
0
{
21125
0
    ImGuiContext& g = *GImGui;
21126
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
21127
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
21128
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21129
0
    bool open;
21130
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21131
0
    if (node->Windows.Size > 0)
21132
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21133
0
    else
21134
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
21135
0
    if (!is_alive) { PopStyleColor(); }
21136
0
    if (is_active && IsItemHovered())
21137
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
21138
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
21139
0
    if (open)
21140
0
    {
21141
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
21142
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
21143
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
21144
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
21145
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
21146
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
21147
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
21148
0
        BulletText("Misc:%s%s%s%s%s%s%s",
21149
0
            node->IsDockSpace() ? " IsDockSpace" : "",
21150
0
            node->IsCentralNode() ? " IsCentralNode" : "",
21151
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
21152
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
21153
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
21154
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
21155
0
        {
21156
0
            if (BeginTable("flags", 4))
21157
0
            {
21158
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
21159
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
21160
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
21161
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
21162
0
                EndTable();
21163
0
            }
21164
0
            TreePop();
21165
0
        }
21166
0
        if (node->ParentNode)
21167
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
21168
0
        if (node->ChildNodes[0])
21169
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
21170
0
        if (node->ChildNodes[1])
21171
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
21172
0
        if (node->TabBar)
21173
0
            DebugNodeTabBar(node->TabBar, "TabBar");
21174
0
        DebugNodeWindowsList(&node->Windows, "Windows");
21175
21176
0
        TreePop();
21177
0
    }
21178
0
}
21179
21180
static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id)
21181
0
{
21182
0
    union { void* ptr; int integer; } tex_id_opaque;
21183
0
    memcpy(&tex_id_opaque, &tex_id, ImMin(sizeof(void*), sizeof(tex_id)));
21184
0
    if (sizeof(tex_id) >= sizeof(void*))
21185
0
        ImFormatString(buf, buf_size, "0x%p", tex_id_opaque.ptr);
21186
0
    else
21187
0
        ImFormatString(buf, buf_size, "0x%04X", tex_id_opaque.integer);
21188
0
}
21189
21190
// [DEBUG] Display contents of ImDrawList
21191
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
21192
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
21193
0
{
21194
0
    ImGuiContext& g = *GImGui;
21195
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
21196
0
    int cmd_count = draw_list->CmdBuffer.Size;
21197
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
21198
0
        cmd_count--;
21199
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
21200
0
    if (draw_list == GetWindowDrawList())
21201
0
    {
21202
0
        SameLine();
21203
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
21204
0
        if (node_open)
21205
0
            TreePop();
21206
0
        return;
21207
0
    }
21208
21209
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
21210
0
    if (window && IsItemHovered() && fg_draw_list)
21211
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21212
0
    if (!node_open)
21213
0
        return;
21214
21215
0
    if (window && !window->WasActive)
21216
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
21217
21218
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
21219
0
    {
21220
0
        if (pcmd->UserCallback)
21221
0
        {
21222
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
21223
0
            continue;
21224
0
        }
21225
21226
0
        char texid_desc[20];
21227
0
        FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId);
21228
0
        char buf[300];
21229
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
21230
0
            pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
21231
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
21232
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
21233
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
21234
0
        if (!pcmd_node_open)
21235
0
            continue;
21236
21237
        // Calculate approximate coverage area (touched pixel count)
21238
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
21239
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
21240
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
21241
0
        float total_area = 0.0f;
21242
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
21243
0
        {
21244
0
            ImVec2 triangle[3];
21245
0
            for (int n = 0; n < 3; n++, idx_n++)
21246
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
21247
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
21248
0
        }
21249
21250
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
21251
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
21252
0
        Selectable(buf);
21253
0
        if (IsItemHovered() && fg_draw_list)
21254
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
21255
21256
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
21257
0
        ImGuiListClipper clipper;
21258
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
21259
0
        while (clipper.Step())
21260
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
21261
0
            {
21262
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
21263
0
                ImVec2 triangle[3];
21264
0
                for (int n = 0; n < 3; n++, idx_i++)
21265
0
                {
21266
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
21267
0
                    triangle[n] = v.pos;
21268
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
21269
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
21270
0
                }
21271
21272
0
                Selectable(buf, false);
21273
0
                if (fg_draw_list && IsItemHovered())
21274
0
                {
21275
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
21276
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21277
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
21278
0
                    fg_draw_list->Flags = backup_flags;
21279
0
                }
21280
0
            }
21281
0
        TreePop();
21282
0
    }
21283
0
    TreePop();
21284
0
}
21285
21286
// [DEBUG] Display mesh/aabb of a ImDrawCmd
21287
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
21288
0
{
21289
0
    IM_ASSERT(show_mesh || show_aabb);
21290
21291
    // Draw wire-frame version of all triangles
21292
0
    ImRect clip_rect = draw_cmd->ClipRect;
21293
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
21294
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
21295
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
21296
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
21297
0
    {
21298
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
21299
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
21300
21301
0
        ImVec2 triangle[3];
21302
0
        for (int n = 0; n < 3; n++, idx_n++)
21303
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
21304
0
        if (show_mesh)
21305
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
21306
0
    }
21307
    // Draw bounding boxes
21308
0
    if (show_aabb)
21309
0
    {
21310
0
        out_draw_list->AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
21311
0
        out_draw_list->AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
21312
0
    }
21313
0
    out_draw_list->Flags = backup_flags;
21314
0
}
21315
21316
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
21317
void ImGui::DebugNodeFont(ImFont* font)
21318
0
{
21319
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
21320
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
21321
0
    SameLine();
21322
0
    if (SmallButton("Set as default"))
21323
0
        GetIO().FontDefault = font;
21324
0
    if (!opened)
21325
0
        return;
21326
21327
    // Display preview text
21328
0
    PushFont(font);
21329
0
    Text("The quick brown fox jumps over the lazy dog");
21330
0
    PopFont();
21331
21332
    // Display details
21333
0
    SetNextItemWidth(GetFontSize() * 8);
21334
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
21335
0
    SameLine(); MetricsHelpMarker(
21336
0
        "Note that the default embedded font is NOT meant to be scaled.\n\n"
21337
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
21338
0
        "You may oversample them to get some flexibility with scaling. "
21339
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
21340
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
21341
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
21342
0
    char c_str[5];
21343
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
21344
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
21345
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
21346
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
21347
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
21348
0
        if (font->ConfigData)
21349
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
21350
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
21351
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
21352
21353
    // Display all glyphs of the fonts in separate pages of 256 characters
21354
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
21355
0
    {
21356
0
        ImDrawList* draw_list = GetWindowDrawList();
21357
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
21358
0
        const float cell_size = font->FontSize * 1;
21359
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
21360
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
21361
0
        {
21362
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
21363
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
21364
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
21365
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
21366
0
            {
21367
0
                base += 4096 - 256;
21368
0
                continue;
21369
0
            }
21370
21371
0
            int count = 0;
21372
0
            for (unsigned int n = 0; n < 256; n++)
21373
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
21374
0
                    count++;
21375
0
            if (count <= 0)
21376
0
                continue;
21377
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
21378
0
                continue;
21379
21380
            // Draw a 16x16 grid of glyphs
21381
0
            ImVec2 base_pos = GetCursorScreenPos();
21382
0
            for (unsigned int n = 0; n < 256; n++)
21383
0
            {
21384
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
21385
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
21386
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
21387
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
21388
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
21389
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
21390
0
                if (!glyph)
21391
0
                    continue;
21392
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
21393
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
21394
0
                {
21395
0
                    DebugNodeFontGlyph(font, glyph);
21396
0
                    EndTooltip();
21397
0
                }
21398
0
            }
21399
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
21400
0
            TreePop();
21401
0
        }
21402
0
        TreePop();
21403
0
    }
21404
0
    TreePop();
21405
0
}
21406
21407
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
21408
0
{
21409
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
21410
0
    Separator();
21411
0
    Text("Visible: %d", glyph->Visible);
21412
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
21413
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
21414
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
21415
0
}
21416
21417
// [DEBUG] Display contents of ImGuiStorage
21418
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
21419
0
{
21420
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
21421
0
        return;
21422
0
    for (const ImGuiStoragePair& p : storage->Data)
21423
0
    {
21424
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
21425
0
        DebugLocateItemOnHover(p.key);
21426
0
    }
21427
0
    TreePop();
21428
0
}
21429
21430
// [DEBUG] Display contents of ImGuiTabBar
21431
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
21432
0
{
21433
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
21434
0
    char buf[256];
21435
0
    char* p = buf;
21436
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
21437
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
21438
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
21439
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
21440
0
    {
21441
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21442
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
21443
0
    }
21444
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
21445
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21446
0
    bool open = TreeNode(label, "%s", buf);
21447
0
    if (!is_active) { PopStyleColor(); }
21448
0
    if (is_active && IsItemHovered())
21449
0
    {
21450
0
        ImDrawList* draw_list = GetForegroundDrawList();
21451
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
21452
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21453
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
21454
0
    }
21455
0
    if (open)
21456
0
    {
21457
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
21458
0
        {
21459
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
21460
0
            PushID(tab);
21461
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
21462
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
21463
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
21464
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
21465
0
            PopID();
21466
0
        }
21467
0
        TreePop();
21468
0
    }
21469
0
}
21470
21471
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
21472
0
{
21473
0
    ImGuiContext& g = *GImGui;
21474
0
    SetNextItemOpen(true, ImGuiCond_Once);
21475
0
    bool open = TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A");
21476
0
    if (IsItemHovered())
21477
0
        g.DebugMetricsConfig.HighlightViewportID = viewport->ID;
21478
0
    if (open)
21479
0
    {
21480
0
        ImGuiWindowFlags flags = viewport->Flags;
21481
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
21482
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
21483
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
21484
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
21485
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
21486
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
21487
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
21488
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
21489
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
21490
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
21491
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
21492
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
21493
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
21494
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
21495
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
21496
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
21497
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
21498
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
21499
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
21500
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
21501
0
        for (ImDrawList* draw_list : viewport->DrawDataP.CmdLists)
21502
0
            DebugNodeDrawList(NULL, viewport, draw_list, "DrawList");
21503
0
        TreePop();
21504
0
    }
21505
0
}
21506
21507
void ImGui::DebugNodePlatformMonitor(ImGuiPlatformMonitor* monitor, const char* label, int idx)
21508
0
{
21509
0
    BulletText("%s %d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
21510
0
        label, idx, monitor->DpiScale * 100.0f,
21511
0
        monitor->MainPos.x, monitor->MainPos.y, monitor->MainPos.x + monitor->MainSize.x, monitor->MainPos.y + monitor->MainSize.y, monitor->MainSize.x, monitor->MainSize.y,
21512
0
        monitor->WorkPos.x, monitor->WorkPos.y, monitor->WorkPos.x + monitor->WorkSize.x, monitor->WorkPos.y + monitor->WorkSize.y, monitor->WorkSize.x, monitor->WorkSize.y);
21513
0
}
21514
21515
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
21516
0
{
21517
0
    if (window == NULL)
21518
0
    {
21519
0
        BulletText("%s: NULL", label);
21520
0
        return;
21521
0
    }
21522
21523
0
    ImGuiContext& g = *GImGui;
21524
0
    const bool is_active = window->WasActive;
21525
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
21526
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
21527
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
21528
0
    if (!is_active) { PopStyleColor(); }
21529
0
    if (IsItemHovered() && is_active)
21530
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
21531
0
    if (!open)
21532
0
        return;
21533
21534
0
    if (window->MemoryCompacted)
21535
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
21536
21537
0
    if (g.IO.ConfigDebugIsDebuggerPresent && DebugBreakButton("**DebugBreak**", "in Begin()"))
21538
0
        g.DebugBreakInWindow = window->ID;
21539
21540
0
    ImGuiWindowFlags flags = window->Flags;
21541
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
21542
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
21543
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
21544
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
21545
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
21546
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
21547
0
    if (flags & ImGuiWindowFlags_ChildWindow)
21548
0
        BulletText("ChildFlags: 0x%08X (%s%s%s%s..)", window->ChildFlags,
21549
0
            (window->ChildFlags & ImGuiChildFlags_Border) ? "Border " : "",
21550
0
            (window->ChildFlags & ImGuiChildFlags_ResizeX) ? "ResizeX " : "",
21551
0
            (window->ChildFlags & ImGuiChildFlags_ResizeY) ? "ResizeY " : "",
21552
0
            (window->ChildFlags & ImGuiChildFlags_NavFlattened) ? "NavFlattened " : "");
21553
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
21554
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
21555
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
21556
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
21557
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21558
0
    {
21559
0
        ImRect r = window->NavRectRel[layer];
21560
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
21561
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
21562
0
        else
21563
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
21564
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
21565
0
    }
21566
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
21567
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
21568
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
21569
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
21570
21571
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
21572
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
21573
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
21574
0
    if (window->DockNode || window->DockNodeAsHost)
21575
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
21576
21577
0
    if (window->RootWindow != window)               { DebugNodeWindow(window->RootWindow, "RootWindow"); }
21578
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
21579
0
    if (window->ParentWindow != NULL)               { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
21580
0
    if (window->ParentWindowForFocusRoute != NULL)  { DebugNodeWindow(window->ParentWindowForFocusRoute, "ParentWindowForFocusRoute"); }
21581
0
    if (window->DC.ChildWindows.Size > 0)           { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
21582
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
21583
0
    {
21584
0
        for (ImGuiOldColumns& columns : window->ColumnsStorage)
21585
0
            DebugNodeColumns(&columns);
21586
0
        TreePop();
21587
0
    }
21588
0
    DebugNodeStorage(&window->StateStorage, "Storage");
21589
0
    TreePop();
21590
0
}
21591
21592
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
21593
0
{
21594
0
    if (settings->WantDelete)
21595
0
        BeginDisabled();
21596
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
21597
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
21598
0
    if (settings->WantDelete)
21599
0
        EndDisabled();
21600
0
}
21601
21602
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
21603
0
{
21604
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
21605
0
        return;
21606
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
21607
0
    {
21608
0
        PushID((*windows)[i]);
21609
0
        DebugNodeWindow((*windows)[i], "Window");
21610
0
        PopID();
21611
0
    }
21612
0
    TreePop();
21613
0
}
21614
21615
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
21616
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
21617
0
{
21618
0
    for (int i = 0; i < windows_size; i++)
21619
0
    {
21620
0
        ImGuiWindow* window = windows[i];
21621
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
21622
0
            continue;
21623
0
        char buf[20];
21624
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
21625
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
21626
0
        DebugNodeWindow(window, buf);
21627
0
        Indent();
21628
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
21629
0
        Unindent();
21630
0
    }
21631
0
}
21632
21633
//-----------------------------------------------------------------------------
21634
// [SECTION] DEBUG LOG WINDOW
21635
//-----------------------------------------------------------------------------
21636
21637
void ImGui::DebugLog(const char* fmt, ...)
21638
0
{
21639
0
    va_list args;
21640
0
    va_start(args, fmt);
21641
0
    DebugLogV(fmt, args);
21642
0
    va_end(args);
21643
0
}
21644
21645
void ImGui::DebugLogV(const char* fmt, va_list args)
21646
0
{
21647
0
    ImGuiContext& g = *GImGui;
21648
0
    const int old_size = g.DebugLogBuf.size();
21649
0
    if (g.ContextName[0] != 0)
21650
0
        g.DebugLogBuf.appendf("[%s] [%05d] ", g.ContextName, g.FrameCount);
21651
0
    else
21652
0
        g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
21653
0
    g.DebugLogBuf.appendfv(fmt, args);
21654
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
21655
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
21656
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
21657
#ifdef IMGUI_ENABLE_TEST_ENGINE
21658
    // IMGUI_TEST_ENGINE_LOG() adds a trailing \n automatically
21659
    const int new_size = g.DebugLogBuf.size();
21660
    const bool trailing_carriage_return = (g.DebugLogBuf[new_size - 1] == '\n');
21661
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTestEngine)
21662
        IMGUI_TEST_ENGINE_LOG("%.*s", new_size - old_size - (trailing_carriage_return ? 1 : 0), g.DebugLogBuf.begin() + old_size);
21663
#endif
21664
0
}
21665
21666
// FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout.
21667
static void SameLineOrWrap(const ImVec2& size)
21668
0
{
21669
0
    ImGuiContext& g = *GImGui;
21670
0
    ImGuiWindow* window = g.CurrentWindow;
21671
0
    ImVec2 pos(window->DC.CursorPosPrevLine.x + g.Style.ItemSpacing.x, window->DC.CursorPosPrevLine.y);
21672
0
    if (window->WorkRect.Contains(ImRect(pos, pos + size)))
21673
0
        ImGui::SameLine();
21674
0
}
21675
21676
static void ShowDebugLogFlag(const char* name, ImGuiDebugLogFlags flags)
21677
0
{
21678
0
    ImGuiContext& g = *GImGui;
21679
0
    ImVec2 size(ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui::CalcTextSize(name).x, ImGui::GetFrameHeight());
21680
0
    SameLineOrWrap(size); // FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout.
21681
0
    if (ImGui::CheckboxFlags(name, &g.DebugLogFlags, flags) && g.IO.KeyShift && (g.DebugLogFlags & flags) != 0)
21682
0
    {
21683
0
        g.DebugLogAutoDisableFrames = 2;
21684
0
        g.DebugLogAutoDisableFlags |= flags;
21685
0
    }
21686
0
    ImGui::SetItemTooltip("Hold SHIFT when clicking to enable for 2 frames only (useful for spammy log entries)");
21687
0
}
21688
21689
void ImGui::ShowDebugLogWindow(bool* p_open)
21690
0
{
21691
0
    ImGuiContext& g = *GImGui;
21692
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
21693
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
21694
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
21695
0
    {
21696
0
        End();
21697
0
        return;
21698
0
    }
21699
21700
0
    ImGuiDebugLogFlags all_enable_flags = ImGuiDebugLogFlags_EventMask_ & ~ImGuiDebugLogFlags_EventInputRouting;
21701
0
    CheckboxFlags("All", &g.DebugLogFlags, all_enable_flags);
21702
0
    SetItemTooltip("(except InputRouting which is spammy)");
21703
21704
0
    ShowDebugLogFlag("ActiveId", ImGuiDebugLogFlags_EventActiveId);
21705
0
    ShowDebugLogFlag("Clipper", ImGuiDebugLogFlags_EventClipper);
21706
0
    ShowDebugLogFlag("Docking", ImGuiDebugLogFlags_EventDocking);
21707
0
    ShowDebugLogFlag("Focus", ImGuiDebugLogFlags_EventFocus);
21708
0
    ShowDebugLogFlag("IO", ImGuiDebugLogFlags_EventIO);
21709
0
    ShowDebugLogFlag("Nav", ImGuiDebugLogFlags_EventNav);
21710
0
    ShowDebugLogFlag("Popup", ImGuiDebugLogFlags_EventPopup);
21711
0
    ShowDebugLogFlag("Selection", ImGuiDebugLogFlags_EventSelection);
21712
0
    ShowDebugLogFlag("Viewport", ImGuiDebugLogFlags_EventViewport);
21713
0
    ShowDebugLogFlag("InputRouting", ImGuiDebugLogFlags_EventInputRouting);
21714
21715
0
    if (SmallButton("Clear"))
21716
0
    {
21717
0
        g.DebugLogBuf.clear();
21718
0
        g.DebugLogIndex.clear();
21719
0
    }
21720
0
    SameLine();
21721
0
    if (SmallButton("Copy"))
21722
0
        SetClipboardText(g.DebugLogBuf.c_str());
21723
0
    SameLine();
21724
0
    if (SmallButton("Configure Outputs.."))
21725
0
        OpenPopup("Outputs");
21726
0
    if (BeginPopup("Outputs"))
21727
0
    {
21728
0
        CheckboxFlags("OutputToTTY", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTTY);
21729
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21730
0
        BeginDisabled();
21731
0
#endif
21732
0
        CheckboxFlags("OutputToTestEngine", &g.DebugLogFlags, ImGuiDebugLogFlags_OutputToTestEngine);
21733
0
#ifndef IMGUI_ENABLE_TEST_ENGINE
21734
0
        EndDisabled();
21735
0
#endif
21736
0
        EndPopup();
21737
0
    }
21738
21739
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), ImGuiChildFlags_Border, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
21740
21741
0
    const ImGuiDebugLogFlags backup_log_flags = g.DebugLogFlags;
21742
0
    g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
21743
21744
0
    ImGuiListClipper clipper;
21745
0
    clipper.Begin(g.DebugLogIndex.size());
21746
0
    while (clipper.Step())
21747
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
21748
0
            DebugTextUnformattedWithLocateItem(g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no), g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no));
21749
0
    g.DebugLogFlags = backup_log_flags;
21750
0
    if (GetScrollY() >= GetScrollMaxY())
21751
0
        SetScrollHereY(1.0f);
21752
0
    EndChild();
21753
21754
0
    End();
21755
0
}
21756
21757
// Display line, search for 0xXXXXXXXX identifiers and call DebugLocateItemOnHover() when hovered.
21758
void ImGui::DebugTextUnformattedWithLocateItem(const char* line_begin, const char* line_end)
21759
0
{
21760
0
    TextUnformatted(line_begin, line_end);
21761
0
    if (!IsItemHovered())
21762
0
        return;
21763
0
    ImGuiContext& g = *GImGui;
21764
0
    ImRect text_rect = g.LastItemData.Rect;
21765
0
    for (const char* p = line_begin; p <= line_end - 10; p++)
21766
0
    {
21767
0
        ImGuiID id = 0;
21768
0
        if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1 || ImCharIsXdigitA(p[10]))
21769
0
            continue;
21770
0
        ImVec2 p0 = CalcTextSize(line_begin, p);
21771
0
        ImVec2 p1 = CalcTextSize(p, p + 10);
21772
0
        g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
21773
0
        if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
21774
0
            DebugLocateItemOnHover(id);
21775
0
        p += 10;
21776
0
    }
21777
0
}
21778
21779
//-----------------------------------------------------------------------------
21780
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL)
21781
//-----------------------------------------------------------------------------
21782
21783
// Draw a small cross at current CursorPos in current window's DrawList
21784
void ImGui::DebugDrawCursorPos(ImU32 col)
21785
0
{
21786
0
    ImGuiContext& g = *GImGui;
21787
0
    ImGuiWindow* window = g.CurrentWindow;
21788
0
    ImVec2 pos = window->DC.CursorPos;
21789
0
    window->DrawList->AddLine(ImVec2(pos.x, pos.y - 3.0f), ImVec2(pos.x, pos.y + 4.0f), col, 1.0f);
21790
0
    window->DrawList->AddLine(ImVec2(pos.x - 3.0f, pos.y), ImVec2(pos.x + 4.0f, pos.y), col, 1.0f);
21791
0
}
21792
21793
// Draw a 10px wide rectangle around CurposPos.x using Line Y1/Y2 in current window's DrawList
21794
void ImGui::DebugDrawLineExtents(ImU32 col)
21795
0
{
21796
0
    ImGuiContext& g = *GImGui;
21797
0
    ImGuiWindow* window = g.CurrentWindow;
21798
0
    float curr_x = window->DC.CursorPos.x;
21799
0
    float line_y1 = (window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y);
21800
0
    float line_y2 = line_y1 + (window->DC.IsSameLine ? window->DC.PrevLineSize.y : window->DC.CurrLineSize.y);
21801
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y1), ImVec2(curr_x + 5.0f, line_y1), col, 1.0f);
21802
0
    window->DrawList->AddLine(ImVec2(curr_x - 0.5f, line_y1), ImVec2(curr_x - 0.5f, line_y2), col, 1.0f);
21803
0
    window->DrawList->AddLine(ImVec2(curr_x - 5.0f, line_y2), ImVec2(curr_x + 5.0f, line_y2), col, 1.0f);
21804
0
}
21805
21806
// Draw last item rect in ForegroundDrawList (so it is always visible)
21807
void ImGui::DebugDrawItemRect(ImU32 col)
21808
0
{
21809
0
    ImGuiContext& g = *GImGui;
21810
0
    ImGuiWindow* window = g.CurrentWindow;
21811
0
    GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col);
21812
0
}
21813
21814
// [DEBUG] Locate item position/rectangle given an ID.
21815
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
21816
21817
void ImGui::DebugLocateItem(ImGuiID target_id)
21818
0
{
21819
0
    ImGuiContext& g = *GImGui;
21820
0
    g.DebugLocateId = target_id;
21821
0
    g.DebugLocateFrames = 2;
21822
0
    g.DebugBreakInLocateId = false;
21823
0
}
21824
21825
// FIXME: Doesn't work over through a modal window, because they clear HoveredWindow.
21826
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
21827
0
{
21828
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
21829
0
        return;
21830
0
    ImGuiContext& g = *GImGui;
21831
0
    DebugLocateItem(target_id);
21832
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
21833
21834
    // Can't easily use a context menu here because it will mess with focus, active id etc.
21835
0
    if (g.IO.ConfigDebugIsDebuggerPresent && g.MouseStationaryTimer > 1.0f)
21836
0
    {
21837
0
        DebugBreakButtonTooltip(false, "in ItemAdd()");
21838
0
        if (IsKeyChordPressed(g.DebugBreakKeyChord))
21839
0
            g.DebugBreakInLocateId = true;
21840
0
    }
21841
0
}
21842
21843
void ImGui::DebugLocateItemResolveWithLastItem()
21844
0
{
21845
0
    ImGuiContext& g = *GImGui;
21846
21847
    // [DEBUG] Debug break requested by user
21848
0
    if (g.DebugBreakInLocateId)
21849
0
        IM_DEBUG_BREAK();
21850
21851
0
    ImGuiLastItemData item_data = g.LastItemData;
21852
0
    g.DebugLocateId = 0;
21853
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
21854
0
    ImRect r = item_data.Rect;
21855
0
    r.Expand(3.0f);
21856
0
    ImVec2 p1 = g.IO.MousePos;
21857
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
21858
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
21859
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
21860
0
}
21861
21862
void ImGui::DebugStartItemPicker()
21863
0
{
21864
0
    ImGuiContext& g = *GImGui;
21865
0
    g.DebugItemPickerActive = true;
21866
0
}
21867
21868
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
21869
void ImGui::UpdateDebugToolItemPicker()
21870
80.5k
{
21871
80.5k
    ImGuiContext& g = *GImGui;
21872
80.5k
    g.DebugItemPickerBreakId = 0;
21873
80.5k
    if (!g.DebugItemPickerActive)
21874
80.5k
        return;
21875
21876
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
21877
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
21878
0
    if (IsKeyPressed(ImGuiKey_Escape))
21879
0
        g.DebugItemPickerActive = false;
21880
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
21881
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
21882
0
    {
21883
0
        g.DebugItemPickerBreakId = hovered_id;
21884
0
        g.DebugItemPickerActive = false;
21885
0
    }
21886
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
21887
0
        if (change_mapping && IsMouseClicked(mouse_button))
21888
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
21889
0
    SetNextWindowBgAlpha(0.70f);
21890
0
    if (!BeginTooltip())
21891
0
        return;
21892
0
    Text("HoveredId: 0x%08X", hovered_id);
21893
0
    Text("Press ESC to abort picking.");
21894
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
21895
0
    if (change_mapping)
21896
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
21897
0
    else
21898
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
21899
0
    EndTooltip();
21900
0
}
21901
21902
// [DEBUG] ID Stack Tool: update queries. Called by NewFrame()
21903
void ImGui::UpdateDebugToolStackQueries()
21904
80.5k
{
21905
80.5k
    ImGuiContext& g = *GImGui;
21906
80.5k
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21907
21908
    // Clear hook when id stack tool is not visible
21909
80.5k
    g.DebugHookIdInfo = 0;
21910
80.5k
    if (g.FrameCount != tool->LastActiveFrame + 1)
21911
80.5k
        return;
21912
21913
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
21914
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
21915
5
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
21916
5
    if (tool->QueryId != query_id)
21917
0
    {
21918
0
        tool->QueryId = query_id;
21919
0
        tool->StackLevel = -1;
21920
0
        tool->Results.resize(0);
21921
0
    }
21922
5
    if (query_id == 0)
21923
5
        return;
21924
21925
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
21926
0
    int stack_level = tool->StackLevel;
21927
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21928
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
21929
0
            tool->StackLevel++;
21930
21931
    // Update hook
21932
0
    stack_level = tool->StackLevel;
21933
0
    if (stack_level == -1)
21934
0
        g.DebugHookIdInfo = query_id;
21935
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
21936
0
    {
21937
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
21938
0
        tool->Results[stack_level].QueryFrameCount++;
21939
0
    }
21940
0
}
21941
21942
// [DEBUG] ID Stack tool: hooks called by GetID() family functions
21943
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
21944
0
{
21945
0
    ImGuiContext& g = *GImGui;
21946
0
    ImGuiWindow* window = g.CurrentWindow;
21947
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
21948
21949
    // Step 0: stack query
21950
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
21951
0
    if (tool->StackLevel == -1)
21952
0
    {
21953
0
        tool->StackLevel++;
21954
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
21955
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
21956
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
21957
0
        return;
21958
0
    }
21959
21960
    // Step 1+: query for individual level
21961
0
    IM_ASSERT(tool->StackLevel >= 0);
21962
0
    if (tool->StackLevel != window->IDStack.Size)
21963
0
        return;
21964
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
21965
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
21966
21967
0
    switch (data_type)
21968
0
    {
21969
0
    case ImGuiDataType_S32:
21970
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
21971
0
        break;
21972
0
    case ImGuiDataType_String:
21973
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
21974
0
        break;
21975
0
    case ImGuiDataType_Pointer:
21976
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
21977
0
        break;
21978
0
    case ImGuiDataType_ID:
21979
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
21980
0
            return;
21981
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
21982
0
        break;
21983
0
    default:
21984
0
        IM_ASSERT(0);
21985
0
    }
21986
0
    info->QuerySuccess = true;
21987
0
    info->DataType = data_type;
21988
0
}
21989
21990
static int StackToolFormatLevelInfo(ImGuiIDStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
21991
0
{
21992
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
21993
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
21994
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
21995
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
21996
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
21997
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
21998
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
21999
0
        return (*buf = 0);
22000
#ifdef IMGUI_ENABLE_TEST_ENGINE
22001
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
22002
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
22003
#endif
22004
0
    return ImFormatString(buf, buf_size, "???");
22005
0
}
22006
22007
// ID Stack Tool: Display UI
22008
void ImGui::ShowIDStackToolWindow(bool* p_open)
22009
0
{
22010
0
    ImGuiContext& g = *GImGui;
22011
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
22012
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
22013
0
    if (!Begin("Dear ImGui ID Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
22014
0
    {
22015
0
        End();
22016
0
        return;
22017
0
    }
22018
22019
    // Display hovered/active status
22020
0
    ImGuiIDStackTool* tool = &g.DebugIDStackTool;
22021
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
22022
0
    const ImGuiID active_id = g.ActiveId;
22023
#ifdef IMGUI_ENABLE_TEST_ENGINE
22024
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
22025
#else
22026
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
22027
0
#endif
22028
0
    SameLine();
22029
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
22030
22031
    // CTRL+C to copy path
22032
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
22033
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
22034
0
    SameLine();
22035
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
22036
0
    if (tool->CopyToClipboardOnCtrlC && Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, ImGuiInputFlags_RouteGlobal | ImGuiInputFlags_RouteOverFocused))
22037
0
    {
22038
0
        tool->CopyToClipboardLastTime = (float)g.Time;
22039
0
        char* p = g.TempBuffer.Data;
22040
0
        char* p_end = p + g.TempBuffer.Size;
22041
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
22042
0
        {
22043
0
            *p++ = '/';
22044
0
            char level_desc[256];
22045
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
22046
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
22047
0
            {
22048
0
                if (level_desc[n] == '/')
22049
0
                    *p++ = '\\';
22050
0
                *p++ = level_desc[n];
22051
0
            }
22052
0
        }
22053
0
        *p = '\0';
22054
0
        SetClipboardText(g.TempBuffer.Data);
22055
0
    }
22056
22057
    // Display decorated stack
22058
0
    tool->LastActiveFrame = g.FrameCount;
22059
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
22060
0
    {
22061
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
22062
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
22063
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
22064
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
22065
0
        TableHeadersRow();
22066
0
        for (int n = 0; n < tool->Results.Size; n++)
22067
0
        {
22068
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
22069
0
            TableNextColumn();
22070
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
22071
0
            TableNextColumn();
22072
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
22073
0
            TextUnformatted(g.TempBuffer.Data);
22074
0
            TableNextColumn();
22075
0
            Text("0x%08X", info->ID);
22076
0
            if (n == tool->Results.Size - 1)
22077
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
22078
0
        }
22079
0
        EndTable();
22080
0
    }
22081
0
    End();
22082
0
}
22083
22084
#else
22085
22086
void ImGui::ShowMetricsWindow(bool*) {}
22087
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
22088
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
22089
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
22090
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
22091
void ImGui::DebugNodeFont(ImFont*) {}
22092
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
22093
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
22094
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
22095
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
22096
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
22097
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
22098
22099
void ImGui::ShowDebugLogWindow(bool*) {}
22100
void ImGui::ShowIDStackToolWindow(bool*) {}
22101
void ImGui::DebugStartItemPicker() {}
22102
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
22103
22104
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
22105
22106
//-----------------------------------------------------------------------------
22107
22108
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
22109
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
22110
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
22111
#include "imgui_user.inl"
22112
#endif
22113
22114
//-----------------------------------------------------------------------------
22115
22116
#endif // #ifndef IMGUI_DISABLE